Monday, September 30, 2013

Enable the keyboard in an Android emulator

After creating an Android application using the great Xamarin tools, it was finally time to do some intensive testing on the Android emulator. When starting to test I noticed something really annoying, I had to type everything through the onscreen keyboard and couldn’t use the physical keyboard on my development machine.

Fixing this is easy by changing the settings of a specific emulator device:

  • Open the AVD Manager.

image

  • Select an emulator device.
  • Click on Edit… to edit the properties of this device. The Edit AVD window is loaded.

image

  • In the Hardware section, click on New... A list is loaded with all the properties you can configure.

image

  • In the Property drop-down list, select Keyboard Support and press OK.

image

  • This add the property in the hardware list.

image

  • Click on the value column and change it to "yes".

image

  • Click on "Edit AVD" once again to save your changes.

Friday, September 27, 2013

Android: Install an apk file on the Android emulator

A colleague created an Android apk package using PhoneGap build and asked me to test it.

But how do you get this apk file on the emulator?

  1. Start the Android emulator(through the AVD manager).
  2. Open a command prompt and navigate to the SDK\platform-tools folder.
  3. Paste the APK file in the 'platform-tools' folder.
  4. Execute the following command.

    adb install [apk file name]

Wednesday, September 25, 2013

Xamarin.Android: error when calling Azure mobile services

In a mobile application I’m building with  Xamarin Android I connect to an Azure Mobile Services backend. Xamarin made this easy by providing an Azure Mobile Services component.

However when I tried to connect to Azure, every call failed with the following error message:

“The authentication or decryption has failed.”

I was able to fix the problem by switching to a more recent Android version in the emulator.

Tuesday, September 24, 2013

Enterprise Library 6 and Unity 3 Hands-on Labs available

A few months after the release of Enterprise Library 6 and Unity 3, Microsoft finally released a set of Hands-on Labs.

The comprehensive labs were created by developers for developers. They will be useful both to those who are new to Enterprise Library and those who are experienced with previous versions of Enterprise Library and would like to learn the new application blocks.

The labs will guide you through common scenarios of using EntLib and Unity in various application contexts, including advanced ones. They should help reduce errors and promote faster skill acquisition.

The labs may also be of value to trainers and academics, since they can be used as teaching aids in the classes devoted to Enterprise Library specifically or in courses on Component-Based Software Engineering, Code Re-use, Enterprise Application Development, or Aspect-Oriented Programming.

Go download them here:

Monday, September 23, 2013

Entity Framework error: There is already an open DataReader associated with this Command which must be closed first

On a recent project I started to use Entity Framework. So far the experience has been good, but sometimes I get some unexpected issues(and I have to force myself to not go back to NHibernate Glimlach).

Let’s have a look at the code first:

I think there’s nothing special about this code. I first load all the categories and then walk through all the products(which will cause a n+1 issue, but that’s another discussion). When I first ran this code it failed with the following error message:

"An error occurred while executing the command definition. See the inner exception for details."

When I drilled down to the innermost exception, the following message was shown:

"There is already an open DataReader associated with this Command which must be closed first."

  To solve this, you have to add an extra part to your connection string:

Data Source=srv01;Initial Catalog=Northwind;Persist Security Info=True;Integrated Security=True;MultipleActiveResultSets=true

Friday, September 20, 2013

Team Foundation Server WorkItem Charts

With the September 9 release of Team Foundation Service, a nice new feature was released that allows you to create charts from your work item query results. Each query now has a new Charts view. From that view you can create charts based on the data returned by the query.

To test the feature, execute the following steps:

image

  • Click on the Queries tab

image

  • Click on the Charts option in the Query view

image

  • Click on New Chart to create your first Chart. The Configure Chart dialog is loaded

image

  • Choose a chart type on the left and a ‘Group by’ option on the right. A preview of the chart is shown.

image

  • Click OK to add the Chart to the Query view.

image

Nice!

Thursday, September 19, 2013

Impress your colleagues with your knowledge about…Environment.FailFast

Sometimes when working with .NET you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is Environment.FailFast.

The FailFast method stops your program immediately, ensuring that no further code can execute. As this means that you cannot report the problem directly to the user, this static method includes a parameter, to which you can provide a string containing a status message. This message is recorded in the application event log.

When is this method useful?

One scenario where this method is useful is when your program can enter an unstable state that introduces the risk of data corruption. If this means that it is not possible to continue with the process safely, it may be necessary to exit the program and report an error. Environment.FailFast allows you to kill the process immediately, ensuring that no further code executes.

Another scenario where you can use it is when you have an application that is giving you some weird output. You know it's wrong, but there are just no exceptions bubbling to the surface to help you out. By putting Environment.FastFail you can log an internal exception and hopefully find out where your problem is.

Here is a code sample:

Notice that when you execute this code, only the ‘start’ message is written to the console.

Wednesday, September 18, 2013

Developing Big Data solutions on Windows Azure

The Pattern and Practices team has released a preview of their new e-book: ‘Developing Big Data solutions on Windows Azure’. The book can be downloaded from the Patterns & Practices Windows Azure Guidance site.

image

Topics Covered in This Book
  • What is Big Data?
  • Getting Started with HDInsight
  • Collecting and Loading Data
  • Performance Queries and Transformations
  • Consuming and Visualizing Results
  • Debugging, Testing, and Automating HDInsight Solutions
  • Managing and Monitoring HDInsight
  • Scenario 1: Iterative Data Exploration
  • Scenario 2: Extra, Transform, Load
  • Scenario 3: HDInsight as a Data Warehouse
  • Scenario 4: Enterprise BI Integration

Tuesday, September 17, 2013

Durandal 2.0 released

Rob Eiseinberg, the creator of the great MVVM framework Caliburn.Micro, has shown his JavaScript skills and build a Singe Page Application framework called Durandal.  A few weeks ago, a 2.0 version of this framework was released introducing a large list of new features and functionality.

What’s new in Durandal 2.0?
  • A streamlined core with a plugin model for official and community extensions.
  • Now lives side-by-side with other 3rd party scripts
  • A new router with no external dependencies. It supports parameterized routes, optional parameters, splats and query strings. The router handles hash change and push state, supports relative child routers, advanced deep linking hooks, convention-based routing, an event model…and more.
  • More powerful composition of screens, components and widgets. We’ve ironed out the kinks in composition by making the callback lifecycle more consistent and more granular. As part of the process we fixed bugs and extended it with new capabilities including: automatic activation, binding of activation data, inline views and templated view part overrides. There is no framework I know of on any platform that can do what Durandal’s composition engine can do. None.
  • Less “gotchas” throughout. Everything works more intuitively and consistently.
  • Two-Way Databinding to PLAIN JS objects. Use the new observable plugin when targeting ES5 browsers and stop having to create Knockout observables. Normal objects just work.
  • New Bower and Raw HTML project options.
  • VSIX support for VS2012 and 2013
  • A Super Kung Fu Mimosa template update, thanks to @dbashford, creator of Mimosa and @CraigCav.
  • An official TypeScript definition file.
  • More and better docs, including a fully deep-linked API doc, generated from the source.
  • Tons of bug fixes, new extensibility points and other improvements.
  • And, of course, there’s an upgrade guide for those moving from 1.x to 2.0.

image

So if you are still looking for a good SPA framework and you like Caliburn.Micro, Durandal would be a good choice for you…

Monday, September 16, 2013

Windows 8–Add a live tile for your website

Windows 8 introduces the concept of ‘live’ tiles.

Microsoft’s explanation of live tiles:

“Live tiles sit on the Windows 8 start screen, and are useful for having instantaneous information on constantly changing data like stock indexes, international weather, as well as local and international news. Live tiles replace the need to visit certain websites that contain this information, something that many PC users do on a daily basis. Live tiles also replace the need to launch any of the apps that provide this information; live tiles provide you with short, immediate updates without having to leave your start screen.”

But did you know that you can also add live tiles for your website? Doing this is easy!

Follow these steps to add live tile support for your website:

image

  • Click on Add Notifications
    • Specify the URL of your RSS feed and click on Get feed.

image

  • Click on Get the Code!
    • Copy the generated meta tags and paste them to the <head> of your HTML page and upload the PNG tile backgrounds to your server.

image

As an extra, you get a nice preview of the result:

image

Friday, September 13, 2013

Building Sharepoint 2013 projects on your TFS Build server

With the release of Visual Studio 2012 and the improved Sharepoint integration, building, packaging and deploying your Sharepoint solutions became a lot easier.

Still if you want to get everything running on your build server, you’ve got some work to do. On your TFS 2012 Build server, the following components need to be installed:

Thursday, September 12, 2013

Responsive Design in Sharepoint

You want to apply Responsive Design in Sharepoint? Have a look at Responsive Sharepoint. It provides  a conversion of popular grid and responsive frameworks to a SharePoint 2010 and SharePoint 2013 version.Today, Twitter Bootstrap and Zurb Foundation are supported.

ResponsiveSharepoint

More information here: http://blogs.msdn.com/b/sharepointdev/archive/2013/04/01/implementing-your-responsive-designs-on-sharepoint-2013.aspx

Wednesday, September 11, 2013

Windows Azure Infographics

Looking for a good high level overview of what Windows Azure has to offer? Take a look at the Windows Azure Infographics. These technical posters are excellent for learning and training.

Following posters are available:

  • Windows Azure: An overview of Windows Azure, features, services and common uses
  • Cloud Services: Scaling an application using Cloud Services, including designing, deploying and tuning.
  • Media Services: The workflow for Media Services, from media creation through consumption.
  • Infrastructure Services: Common scenarios for Infrastructure Services.
  • Integration Platform: The MS integration platform, including enterprise integration with the cloud.
  • Mobile Gaming: The features for gaming, including data, computing, authentication and media.
  • Mobile Services: Features and capabilities, including storage, authentication, push notifications, and custom server-side code

image

Tuesday, September 10, 2013

ASP.NET MVC 4: Error when using anti-forgery token in combination with claims-based authentication

Enabling Claims Based authentication on your ASP.NET MVC project is easy:

  • Create a new ASP.NET MVC web application
  • Right click on the project and choose the Identity and Access… option(if you don’t see this option, make sure that you have the Identity and Access Tool extension installed)
  • Walk through the configuration wizard and… done!

But when I tried to do this on a new project, it failed with the following error:

“A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was not present on the provided ClaimsIdentity. To enable anti-forgery token support with claims-based authentication, please verify that the configured claims provider is providing both of these claims on the ClaimsIdentity instances it generates. If the configured claims provider instead uses a different claim type as a unique identifier, it can be configured by setting the static property AntiForgeryConfig.UniqueClaimTypeIdentifier.”

clip_image002

Woops! This approach has always worked for me. So something must have been changed. And indeed, I was using an ASP.NET MVC 4 project where before I was using ASP.NET MVC 3.

Using Html.AntiForgeryToken in MVC 4 has changed slightly from the previous version if you’re building a claims-aware application. In prior versions User.Identity.Name was included in the anti-forgery token as a way to validate the <form> being submitted, but in MVC 4 if the identity is IClaimsIdentity (WIF) or ClaimsIdentity (.NET 4.5) then the anti-forgery token attempts to put one or more claim values into the anti-forgery token.

The problem is which claim(s) should it use? The value needs to uniquely identifier the user, so by default MVC expects the nameidentifier and the identityprovider  If you’re using the Windows AzureACS as your STS then you’re all set. If you’re not using ACS then you’ll see the same error I had.

You can solve it by telling ASP.NET MVC which claim you want to use to uniquely identify the user. You do this by setting the AntiForgeryConfig.UniqueClaimTypeIdentifier property:

Monday, September 9, 2013

ASP.NET Web API: HttpContext.Current is null inside Task

A few days ago, a colleague asked my help to solve an issue he had with ASP.NET Web API. His code looked like the following:

The problem was that HttpContext.Current was always null after switching to another task.

When I tried to reproduce the issue by building a similar sample on my computer, it just worked. The only difference between his code and mine was that I created an ASP.NET Web API 4.5 application, where he was still using ASP.NET 4.

So switching to .NET 4.5 solved the problem. But why? It seems that in ASP.NET 4.5, a task friendly synchronization context got introduced. This synchronization context ensures that the originel context is restored after leaving the await block.

So make sure that you either:

  • Set httpRuntime.targetFramework to 4.5, or
  • In your appSettings, set aspnet:UseTaskFriendlySynchronizationContext to true.

Some more information can be found here.

Friday, September 6, 2013

Team Foundation Server 2012/Service: Create events from web access for other user

I always enjoy browsing through Team Foundation Service, the cloud version of  TFS.  Every day I discover new functionality and features.

Last week I noticed that administrators are able to create team alerts for other users. You could already do this by using the Alerts Explorer from the TFS Power Tools but then those alerts are actually owned by the person creating them and not able to be managed, edited, or disabled for the person they are intended. Afterwards I went back to our on premise TFS environment to notice that the same functionality was also available there… Glimlach

To use this feature:

  • Open the Team Foundation Server web access
  • Browse to a specific Team Project
  • Click on the configuration icon in the right corner to go the configuration section

image

  • On the Overview page click on a Team name:

image

  • On the Team configuration page, click on alerts

image

  • In the Administrator actions on the left, you can search for another user

image

  • After selecting a user, you can manage his events on the right

image

More information here: http://www.edsquared.com/2012/02/09/Creating+EMail+Alerts+For+Team+Members+In+TFS.aspx

Thursday, September 5, 2013

IIS error: Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel’

The last months my laptop started to act strange, 2 or 3 random crashes a day, USB ports that started to fail, extreme CPU usage and so on… And yes, all doctors gave the same diagnosis, my pc was dying. So I took a backup almost every day until it finally happened, one final crash and my system was gone.

After getting a new laptop I started to reconfigure my development environment. After installing IIS I tried to open an existing WCF service and was welcomed by the following yellow screen of death:

“Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.”

clip_image001

This error occured because I installed IIS the .NET Framework 4.

Solving this problem isn’t hard, just open up the ASP.NET IIS Registration Tool (Aspnet_regiis.exe,) to register the correct version of ASP.NET. This can be accomplished by using the –iru parameters when running aspnet_regiis.exe as follows:

aspnet_regiis.exe –iru

That’s it!

Wednesday, September 4, 2013

Unity 3.0 and Enterprise Library 6: Attribute based Policy Injection

For some time, Microsoft Unity supports the concept of Interception. It allows you to inject cross cutting concerns into your code by intercepting method calls and giving you the opportunity to execute some extra code before and after the call.

One of the nice features is that it integrates well with the Microsoft Patterns and Practices Enterprise Library Application Blocks(pfew, what a long name). So you can easily add for example caching or exception handling to your application without having to write the same code over and over again.

Until Enterprise Library 5.0 this was all encapsulated in a separate application block, the Policy Injection application block. Starting from Enterprise Library 6 this block is gone, although the same functionality should still be available inside the Unity.Interception DLL.

When upgrading to Enterprise Library 6.0, I was able to recreate most scenario’s by using this DLL. The only thing I had some trouble with finding out is how to combine Attribute based interception(where you indicate the interception calls by adding attributes on top of your methods) and existing objects. I found a lot of examples where the interception was applied when creating an object through the IoC container, but none when you have an existing object and want to apply interception techniques.

So for anyone who struggled with the same issue, here is the code I used to get this scenario working:

Tuesday, September 3, 2013

Entity Framework Code First: Invalid column name

Last week I was creating a sample project to show some of the Entity Framework Code First features. I only had an old Northwind database available so I mapped my model against this database.

But after writing and running my first test I was welcomed by a nice error message:

Test Name:        CanLoadSuppliersByProductCategoryName

Test FullName: Test.Data.Tests.SupplierRepositoryTests.CanLoadSuppliersByProductCategoryName

Test Source:      c:\Projects\Sample\Tests\SupplierRepositoryTests.cs : line 22

Test Outcome: Failed

Test Duration:   0:00:00,784

Result Message:             

System.Data.EntityCommandExecutionException : An error occurred while executing the command definition. See the inner exception for details.

  ----> System.Data.SqlClient.SqlException : Invalid column name 'Category_CategoryID'.

Invalid column name 'Supplier_SupplierID'.

Result StackTrace:         

at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

at System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)

at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)

at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()

at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator()

at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()

at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)

at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)

at Test.Data.SupplierRepository.LoadSuppliersBy(String productCategoryName) in c:\Projects\Sample\Repositories\SupplierRepository.cs:line 19

at Test.Data.Tests.SupplierRepositoryTests.CanLoadSuppliersByProductCategoryNameLinq() in c:\Projects\Sample\Tests\SupplierRepositoryTests.cs:line 26

--SqlException

at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)

at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)

at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()

at System.Data.SqlClient.SqlDataReader.get_MetaData()

at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)

at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)

at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)

at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)

at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)

at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)

at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)

at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)

Let’s have a look at my code first model:

At first sight, I couldn’t find anything wrong with this model. But after some investigation I discovered that Code First is following some very specific conventions. In my current model I only specified the navigation property but not the related id property. On the Product class I had a ‘Category’ property but not a ‘CategoryId’ one, same thing for the ‘Supplier’ property. So I fixed it by adding these 2 extra properties on the Product class:

Monday, September 2, 2013

Microsoft Unity Dependency Injection finally available on Windows Phone 8

Good news! Microsoft has finally ported Unity DI Container to Windows Phone 8. The Unity NuGet package now contains a version for:

  • The full .NET framework.
  • The NetCore version (for Windows Store apps).
  • The WP8 version.

unity_support