Blog Archives

I’m speaking at TechDays 2012

The last few years I have been attending the DevDays (which are now callled TechDays) and always had alot of fun being there with colleagues, catch up with some guys and learning alot of the sessions being held during these days. This year will be totally different, because this year I will be doing a session myself.

I will be speaking about developing Metro style apps in Windows 8 with Javascript. In this session I will guide you through the different steps to build your own ‘metro style’ app. In this session I will cover the following topics:

  • Promisses
  • Dataloading with XHR (asynchronous)
  • Datatemplates
  • Databinding
  • Adding controls to the AppBar
  • Livetiles
  • Navigation

For most of the above points I will also show you in demo’s how to do this by yourself. I’m pretty sure that after this session you will say: “Wow, that’s really easy to start developing ‘Metro style’ apps with Javascript!”.

I really hope to see you on Friday 17 february in Den Hague! More details about my session can be found at the Techdays site

Last thing to say is that I’m really proud to have this opportunity to speak at an event like this size.

See you there!

Creating a dynamic layout with XAML in Windows 8 ‘Metro style’ apps

A big percentage of all apps is showing data to the user, formatted in different ways. Sometimes it are images, the other time graphs, but a lot of times you use a data grid to present your data to the user. To present this data in the most smooth way to the user, you often want to make the columns / rows scalable. With this approach the data is shown in the most comfortable way to the user when they use different devices and resolutions. When using XAML in your Windows 8 metro style app, you can easily define a dynamic layout for your grid by using the ColumnDefinition and/or RowDefinition classes.

Below I will show you the XAML of an dynamic layout grid and will tell you about the used properties and how to add controls to the different positions created in the grid.

1 <Grid x:Name="LayoutRoot" Background="#FF0C0C0C"> 2 <Grid.ColumnDefinitions> 3 <ColumnDefinition Width="Auto" /> 4 <ColumnDefinition Width="*" /> 5 <ColumnDefinition Width="Auto" /> 6 <ColumnDefinition Width="2*" /> 7 </Grid.ColumnDefinitions> 8 </Grid>

As you can see above right now we only use the ColumnDefinitions to define the columns in our grid. You can see this as the skeleton for our grid. Later we will make sure that every columndefinition will have the right controls added to it.

In this article we only focus on the (easy) dynamic part of the layout. In later articles I will talk about a more complex dynamic layout. That’s why we for now will only talk about the Width property. The Width property can be assigned with the following values: Auto, * or a double value.

Auto The size is determined by the size properties of the content object.
* The value is expressed as a weighted proportion of available space.
Double value The value is expressed in pixels.

So if you have a columndefinition with width set to Auto and you add a control to the column that has a width of 100 pixels, than your column will be 100 pixels + a small amount needed for borders etc. You can see Auto as the fit to content option.

* is the option if you want to make sure that your grid is filled up 100%, because this one will fill up the space that is left after all other columndefinitions have taken their space. If you have multiple columns with Width=”*” than the width will be equally divided over the columns. In our example you see that the third column definition has the width set to “2*”. This means that this column will take up twice as much space as the other column. If there is for example 300 pixels left in our grid, than column 1 will get 100 pixels and column 3 will get 200 pixels.

The last option is setting a width to a double value. This value is the exact value in pixels that the column will take.

Adding controls to the grid

Okay, lets add some controls to the grid to see how that works. First I will show you the full example of the dynamic layout grid, further I will explain what’s happening.

1 <Grid x:Name="LayoutRoot" Background="#FF0C0C0C"> 2 <Grid.ColumnDefinitions> 3 <ColumnDefinition Width="Auto" /> 4 <ColumnDefinition Width="*" /> 5 <ColumnDefinition Width="Auto" /> 6 <ColumnDefinition Width="2*" /> 7 </Grid.ColumnDefinitions> 8 <TextBlock Width="Auto" Text="Column 1" Grid.Column="0"></TextBlock> 9 <Button Width="Auto" Content="Column 2" Grid.Column="1"></Button> 10 <TextBlock Width="Auto" Text="Column 3" Grid.Column="2"></TextBlock> 11 <Button Width="Auto" Content="Column 4" Grid.Column="3"></Button> 12 </Grid>

As you can see in the above example we just start adding controls to are grid right after the ColumnDefinitions element. In our example we added two text blocks and two buttons. With the Grid.Column property we can define in which column these controls are added. Adding the controls to the grid can be done in a random order if you want. As you can see the Grid.Column property is a zero-based index.

Below is a screenshot of the dynamic layout that we created with the above XAML code.

DynamicLayout

You can repeat these above steps in the same way for rows. But than in the Grid.RowDefinitions. If you want to add a control to a specific row in your grid you should add the Grid.Row property to your control to define the row where you want your control to appear.

In a later post I will talk about a more complex dynamic layout and how you can measure the width/height of the columns/rows that are created with the * option. Also we will have a look at how work with these kind of layouts from the code behind.

MySQL sessionState provider adding strange ID to MVC3 url

Tonight I was working on an MVC3 project, which uses an MySQL database. For the admin area I’m using the MySQL membership provider to add users and roles. While clicking through the ASP.NET configuration wizard I have enabled all options for the MySQL membership provider.

After I ran the configuration wizard I started my project to check if the users and roles where working. It didn’t. HttpPost actions where not executed, instead the HttpGet action was executed. After a while I found out that there was a strange kind of folder / query string added to my url.

http://localhost/(S(0swhj3f12244dysv5nj445gx))/

I really had no idea where this thing came from. Compared my solution to another solution (I first checked if this solution was still working) and after a while I found out that my other solution was only using a few options of the MySQL membership provider. Than I started removing parts of the membership that I don’t really needed. After removing the sessionState provider the url was working normal again.

See below codeblock that I removed from my solution

1 <sessionState mode="Custom" cookieless="true" regenerateExpiredSessionId="true" customProvider="MySqlSessionStateProvider"> 2 <providers> 3 <add name="MySqlSessionStateProvider" type="MySql.Web.SessionState.MySqlSessionStateStore, MySql.Web, Version=6.4.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" 4 applicationName="my app" description="my app" connectionStringName="MyAppDB" writeExceptionsToEventLog="False" autogenerateschema="True" /> 5 </providers> 6 </sessionState>

Well that’s it. Seems like that MySQL sessionstate and MVC3 are not really working together.

I haven’t checked out why this behavior is occurring or if it’s also happening when using the ‘standard’ sessionstate provider. If you have any ideas please let me know.

“Integrate" Bing Maps directions in your WP7 app

in the upcoming “Mango” update for Windows Phone 7, Microsoft has already released the Windows Phone Developer Tools Beta 2 for this new version which has got version number 7.1.

One of the new cool features which is included in this beta release is the support to use the “Directions” feature in Bing Maps from your app. This feature makes it very easy to make a location aware app and makes it interactive to the user to help him find a specific spot. (Think about an app that helps users find only your restaurants, ATM’s, your company or anything else that has a coordinate)

Please note that I’m trying to keep away from the “integrate” part, cause actually it’s not integrating but more like navigating away from your app to Bing Maps with the location you specified in your app.

Okay, bring on this new feature and show us how to do this.

First, let’s start with the introduction of this feature/class/task or how you want to call it. We are talking about the BingMapsDirectionsTask which is a very simple class that lives in the Microsoft.Phone.Tasks namespace. You can use this task to create a route on Bing Maps from your app. In short terms this class has three important objects (2 properties / 1 method). It has a Start and an End property, and a method Show() which is it.

Both properties are of type LabeledMapLocation, which have a constructor that expected a string for the name and GeoCoordinate for the location.

In general below code will be enough to create a route on the Bing Maps app:

1 BingMapsDirectionsTask directionTask = new BingMapsDirectionsTask(); 2 directionTask.Start = new LabeledMapLocation("Start", new GeoCoordinate(52.512794, 6.091539)); 3 directionTask.End = new LabeledMapLocation("End", new GeoCoordinate(52.512794, 6.091539)); 4 5 directionTask.Show();

Just three lines of code. Can it be easier?

Yes it can!

If you don’t assign a value to the start property than it will automatically take your location and calculate a route to your End location.

I have created a sample solution where you can use the locations from the emulator to specify a start location and when you click on the map it will take your position (which is set by the emulator) and calculate a route to the location you have clicked.

BingMapsLocationChooser

Choose a location by using the Additional tools.

BingMapsDirections

And there it is our own created direction in the Bing Maps app.

To be honest I’m a bit in doubt about what I think about this feature. On one side it’s a very handy, easily to implement feature that will give you navigation/routing to your location in minutes.

Another thought I still have is I’m adding a map control to my app, a user clicks around and if it needs to calculate a route it exits my app, and starts Bing Maps. No real integration.

Anyone having some thoughts about it?

Download:

Updated language support in Windows Phone 7 “Mango”

In the first release of Windows Phone 7 there was support for a few languages (English (US and UK), French, German, Italian, and Spanish.) With the Mango update Microsoft is adding 17 more languages: Brazilian Portuguese, Chinese (simplified and traditional), Czech, Danish, Dutch, Finnish, Greek, Hungarian, Japanese, Korean, Norwegian (Bokmål), Polish, Portuguese, Russian, and Swedish.

 

As I blogged earlier about the Windows Phone 7 directions button missing and how to get your directions button back. This feature is with Mango updated with support in 19 countries. As you can see in below list of features and in which language it is supported, the “Local search results” or “Scout”  as it is called either, will only be available (for now) in the Windows Phone 7 “Launch” countries. Note that if you set your browser & search language to a non supported language than the “Scout” button will disappear from the Bing Maps menu bar.

 

ScoutButton <= That’s the one you’re missing if you are setting the Browser & Search language to a non Local search results country.

 

  • Bing search (accessed from the phone’s hardware Search button) is available in 33 countries: Argentina, Australia, Austria, Belgium, Brazil, Canada, Denmark, Finland, France, Germany, Hong Kong, India, Indonesia, Ireland, Italy, Japan, Korea, Malaysia, Mexico, Netherlands, New Zealand, Norway, Philippines, Portugal, Russia, Singapore, South Africa, Spain, Sweden, Switzerland, Taiwan, United Kingdom, and the United States. (Elsewhere, handset and mobile operators can configure the hardware search button to a locally-relevant search site).
  • Local search results show up in 6 countries: Australia, Canada, France, Germany, United Kingdom, and the United States.
  • Maps is supported in 19 countries: Australia, Austria, Belgium, Brazil, Canada, Denmark, Finland, France, Germany, Italy, Netherlands, New Zealand, Portugal, Singapore, Spain, Sweden, Switzerland, United Kingdom, and the United States.
  • Voice-to-text and Voice-to-dial is available in 6 countries: France, Germany, Italy, Spain, United Kingdom, and the Unites States.
  • Voice search is supported in 4 countries: France, Germany, United Kingdom, and the United States.

 

One nice thing to mention about the language and region settings is that there are a lot of settings which in Mango don’t require your device to be restarted, but can be applied instant. That makes it easier to play around with these settings and find your own favorite.

 

Language support source:

http://www.everythingwm.com/microsoft-details-language-support-in-mango-update-for-windows-phone/2011/07/11/#more-4824

Extending the Func<T> delegate in .Net 3.5

Today I was working with the Func<T> delegate in my code. I was testing it at my local development machine in a .Net 4.0 console application. (Side information: I was trying to create a sort of overloaded methods which end up in a generic caching method, that has the ability to call the orginal method to get data when there is no data found in the cache.)

My data method has five arguments in the signature and I was writing the following methods:

Generic caching method:

private static TResult PerformCaching<TResult>(Func<TResult> func, string cacheKey)
{
    var cachedData = Get<object>(cacheKey); // <= check if there is data in the cache. 

    if (cachedData == null)
    {
        return func.Invoke(); // <= if not invoke the delegate. 
    }

    return (TResult)cachedData;
}

Public caching method:

public static TResult PerformCaching<TResult, T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5, TResult> func, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, string cacheKey)
{
    return PerformCaching(() => func(arg1, arg2, arg3, arg4, arg5), cacheKey);
}

 

Running this in my .Net 4.0 console application works like a charm. However when I tried to implement this in our SharePoint 2010 project, which is running .Net 3.5 it’s giving me an error in my Error console:

Using the generic type ‘System.Func<TResult>’ requires 1 type arguments

Ok, time to grab reflector and see what’s happening under the hood: I have loaded the .Net 3.5 System.Core.dll manually. (In my case Reflector is starting up with default .Net 4.0) I see the following:

SystemCoreNet35

Both Action<T> and Func<T> have a maximum support for four generic arguments in .Net 3.5.

 

Okay, let’s compare this to .Net 4.0 where my example with five arguments is working like a charm.

SystemCoreNet40

 

From .Net 4.0 on there is support for 16 generic parameters in your Func<T> delegate. Ok, very nice this support in .Net 4.0, but SharePoint 2010 is still running .Net 3.5 and probably will not be updated to .Net 4.0. How can we fix this issue in .Net 3.5?

Well, that will be very easily been fixed with one line of code Emoticon met brede lach.

In our code we add ourselves a Func<T> delegate with the five needed generic arguments like below:

public delegate TResult Func<T1, T2, T3, T4, T5, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); 

Now you can compile your .Net 3.5 project and it’s supporting this five arguments Func<T> delegate. Now say how easy was that?

One of the issues that interests me is the part that when I look into the .Net 4.0 System.Core DLL, the Func<T> delegate starts with Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> and not with Func<T1, TResult>. I tried to found out where the other Func<T>’s have gone, and found out that these have a TypeForwardedFrom attribute like below:

[TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]

The link gives the explanation I think very clear `Type forwarding allows you to move a type to another assembly without having to recompile applications that use the original assembly.`

Well that´s it about extending the Func<T> delegate, hope it will be helpful for you. If you have any questions or remarks please let me know in the comments.

Getting your Enterprise Library performance counters to work.

This week I have been extensively been working with Enterprise Library 5.0 .(Also called as EntLib) In most of the cases Enterprise Library works in the background and it is not always that clear about what’s happening under the hood. Well, this applied for me either this week. I’m using the Caching Application Block of Entlib and was curious about how this performed (how many items are there in the cache list, how many expirations occur, are expired items removed etc.)

First step I took was installing the EntLib instrumentation which can be installed by executing1 a .bat file which comes with the installation of Entlib.

1 Note that executing this batch file should be done with administrator privileges.

InstallInstrumentation

 

Actually I thought that this was it. All that I had to do was adding the counters in performance monitor (PerfMon) and see what happing under the hood. When I was trying to add the counters to PerfMon, I saw that the instrumentation installation has succeeded, because the counters where there.

EntLibPerformanceCounters

 

But adding the counters was not possible. After some searches on the internet I found out that you have to enable performance counters in your application before you can add them to PerfMon to see what’s going on down there.

There are two ways of enabling your application to use performance counters. One is by using the configuration tool which is shipped with EntLib, or manually update your .config file with some references to EntLib dll’s and adding a configuration section. I’ll start with the first one, which is the easiest and is doing the adding part to the .config file for you.

Updating the .config file by use of the EntLib tool:

Start the EntLib configuration tool (Can be found under: All programs => Microsoft patterns & practices => Enterprise Library 5.0 => Enterprise Library Configuration) that fits to the .Net framework you’re using in your application. In my case that will be the X86 .Net 4.0 framework.

When the configuration tool is loaded, choose File => Open, navigate to your .config file and open it. Once it is opened, choose Blocks => Add Instrumentation Settings

AddInstrumentationSettings

 

Expand the Instrumentation settings block and set performanceCountersEnabled to true. Save the settings, so they will be written to your .config file. If you restart your application after saving, and then try to add a performance counter again, you will see that your process is added to the list of instances and that you’re able to add the counters.

 

Updating the .config file manually:

I can imagine that if you’re in the situation that you don’t have the configuration tool available to adjust your .config file (Like me on the production environment) you want to insert these settings manually. Below I will show you how and where to enter these settings in your config file to make this work.

The first step will be to open your .config file in your favorite (or the available) editor.

Now we have to add two parts to the config file. First one is the reference to EntLib to make sure the compiler knows what you mean when you say that you would like to enable the performance counters.

We do that by adding a new ConfigSection. Within this configsection we add a section where we reference the EntLib 5.0 resources like below.

1 <configSections> 2 <section name="instrumentationConfiguration" 3 type="Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation.Configuration.InstrumentationConfigurationSection, 4 Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 5 requirePermission="true" /> 6 </configSections>

The second part is setting the performance counters to enabled, which can be done with below code:

1 <instrumentationConfiguration performanceCountersEnabled="true" />

That is it! Pretty easy as you know how and where to configure it.

Using HttpServerUtility.Transfer with IHttpHandler

Last week I was working on some kind of lightweight downloadhandler where i could pass some information from one page to the downloadhandler by using the HttpContext.Items collection.

To be able to use the HttpContext.Items collection on the downloadhandler, I have to use the HttpServerUtility.Transfer() method (details can found at MSDN), which sends the HttpContext to the page we’re transferring to. When looking at MSDN, I found out that there is an overload for HttpServerUtility.Transfer(IHttpHandler, Boolean) which takes IHttpHandler and a Boolean as parameters.

Nice…. at least that’s what I thought then. There wasn’t that many documentation about using this overload, so I gave it a try.   First I created my DownloadHandler as below: 

public class DownloadHandler : IHttpHandler
{
    public bool IsReusable
    {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context)
    {
        var content = context.Items["Content"].ToString();
        var fileType = context.Items["FileType"].ToString();
        var fileName = "CSV_" + DateTime.Now.ToString() + fileType;

        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.Clear();
        context.Response.ContentType = "application/ms-excel";
        context.Response.AddHeader("content-disposition", "inline;filename=" + fileName);

        context.Response.Write(content);
        context.Response.End();

    }
}

And from my webpage did a call to HttpServerUtility.Transfer() like below:

protected void Page_Load(object sender, EventArgs e)
{
    Context.Items.Add("Content", "colum1;column2;column3");
    Context.Items.Add("FileType", ".csv");

    DownloadHandler handler = new DownloadHandler();
    Server.Transfer(handler, true);
}

I run the project and BOOM:

Error executing child request for handler WebApplication3.DownloadHandler’.


Initial I thought that it was the Boolean parameter which is causing the ViewState to be preserved and when calling the handler that would be indicated by IIS as not valid for this page. Setting the Boolean to false resulted in the same error.

I searched a bit on Google but couldn’t find a good answer why this was not working. So I used Reflector to check the .Net assembly to see what’s happening in that Transfer() method. (HttpServerUtility can be found in the System.Web dll.) And to my surprise I saw the following code within that method:

public void Transfer(IHttpHandler handler, bool preserveForm)
{
    Page page = handler as Page;
    if ((page != null) && page.IsCallback)
    {
        throw new ApplicationException(SR.GetString("Transfer_not_allowed_in_callback"));
    }
    this.Execute(handler, null, preserveForm);
    this._context.Response.End();
}

If the handler is not of type Page than it will definitly be null. That’s what exactly is happening in my case. Second thought about it is that if handler could be of type Page, than Page will implement IHttpHandler. Let’s have a look at the Page class in Reflector. (Page can be found in System.Web.UI dll.) And there it is:

public class Page : TemplateControl, IHttpHandler
{
}

And our implementation of the ProcessRequest method:

[EditorBrowsable(EditorBrowsableState.Never)]
public virtual void ProcessRequest(HttpContext context)
{
    if ((HttpRuntime.NamedPermissionSet != null)           !HttpRuntime.DisableProcessRequestInApplicationTrust)
    {
        if (!HttpRuntime.ProcessRequestInApplicationTrust)
        {
            this.ProcessRequestWithAssert(context);
            return;
        }
        if (base.NoCompile)
        {
            HttpRuntime.NamedPermissionSet.PermitOnly();
        }
    }
    this.ProcessRequestWithNoAssert(context);
}

As you can see ProcessRequest is virtual, so we can override it with our own implementation. With this information I updated my DownloadHandler class to derive from Page instead of direct from IHttpHandler and override the ProcessRequest method. The DownloadHandler class will look like below:

public class DownloadHandler : Page
{
    public override void ProcessRequest(HttpContext context)
    {
        var content = context.Items["Content"].ToString();
        var fileType = context.Items["FileType"].ToString();
        var fileName = "CSV_" + DateTime.Now.ToString() + fileType;

        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.Clear();
        context.Response.ContentType = "application/ms-excel";
        context.Response.AddHeader("content-disposition", "inline;filename=" + fileName);

        context.Response.Write(content);
        context.Response.End();
    }
}

When running this code the file is outputted to the browser and after that the request is ended. I have added also the Page_Load and OnPreRender events, but there not executed in this sample. That’s a good thing, because right now we have our lightweight downloadhandler which is working in a very early stage of the Page lifecycle. (Actually it’s happening before the page lifecycle.)Well, I hope that this will help someone who is also trying to use this overload and is facing the same issues with the implementation.

VS2010 SP1 Beta released

Today the beta off service pack 1 for Visual Studio 2010 is released. Scott Hanselman has a very nice blogpost about it

The mayor updates within this service pack are the following:

  • VS 2010 SP1 Beta
  • ASP.NET MVC 3 RC2
  • Razor Tooling
  • SQL Compact Edition 4 Beta
  • Entity Framework 4 Code First (CTP5)

Some other features which I personaly really like are:

  • Unittests will support .Net 3.5
  • Intellitrace for X64 and Sharepoint projects

For now it’s still a beta version, the final version is expected to be shipped around March/April 2011.

You can read the whole article on Scott Hanselmans blog.

http://www.hanselman.com/blog/VisualStudioExplosionVS2010SP1BETAReleasedAndContext.aspx

Windows phone 7 directions button missing

When playing around in Windows Phone 7 I noticed that the Bing Maps functionality has a very nice and fast way to calculate a route from the point where you are by pressing the Directions button. (Your current location is determined by the A-GPS sensor in your WP7 device.) When calculating the route you have the choice to calculate a route driven by a car, or for walking.  Also finding a location on the map works easy by pressing the Find button and type a location or just speak to your phone to find it :) . When selecting details of the calculated route it smoothly zooms to the selected location. Very nice done.

“Current location on Bing Maps”

Normally I don’t use navigation a lot, but on my last vacation I was kind of lost the way back to my vacation home. I thought no problem at all, get my WP7 phone, start Bing Maps and voila find the route back home. WRONG…… Bing Maps was starting up and my current location was found within seconds, but there was no way to calculate a route or find a location on the map. The directions button was just disappeared. And when I tried to find a location, it only searches the internet and not the map. After a few tries Idecided to pickup my hardcopy map and navigate my way back on the ‘old school’ way. At that moment I was thinking that I did something wrong or that the internet connection wasn’t stable enough to calculate the route.

“Details of the calculated route on Bing Maps”

Back home I gave it another few tries, but without luck. Than I start thinking what settings do I have changed since I got my device. After a while I found out that I have changed the region settings from English to Netherlands. I have reverted this change, restarted my device and yes…….my directions button is back again.

I took the following steps to get my Directions and Find  functionality back on the Bing Maps:

1. Go to Settings

2. Open Region & Language

3. Change Browser & search language to English (United States)

4. Click on the link on top of the screen to accept the changes and restart your device.

I think that this functionality is only available in the languages in which WP7 is official launched. I will update this settings back to Netherlands when WP7 is officially launched in the Netherlands.