Friday, March 29, 2013

Web API file upload set filename

By default when you upload files using ASP.NET Web API, the files are saved using a random filename.

WebApiFileUpload

This is not a bug, but a security decision Microsoft made. They considered it a security risk to take the file name provided in the Content-Disposition header field and decided  instead to compute a file name.

You can easily solve this by deriving from the default MultiPartFormDataStreamProvider and provide your own naming mechanism:

If you want to know some more about uploading files using Web API, I recommend the following blog post: A guide to asynchronous file uploads in ASP.NET Web API RTM

Thursday, March 28, 2013

Running web deploy from the command line: some useful commands

I talked about Web Deploy before. It allows you to easily deploy your web applications to IIS without much overhead. I use it most of the time. Last week I asked the server administrator to enable the automatic backup feature on the web server. 

Once I got the confirmation email that it was configured, I did a new deployment to test the backup feature.

After the deployment completed succesfully, I opened a command prompt and browsed to C:\Program Files (x86)\IIS\Microsoft Web Deploy V3.

Print the list of backups

I used the following command to dump the list of created backups:

msdeploy -verb:dump -source:backupManager="development.customer.be/appname",computerName="serverXX",userName="UserXYZ",password="PasswordXYZ"

But the output window returned nothing. No backups were created.

Print the backup settings

I switched to another command to dump the backupSettings from the server:

msdeploy -verb:dump -source:backupSettings="development.customer.be/appname",computerName="serverXX",userName="UserXYZ",password="PasswordXYZ"

This time I got some information back:

Info: Using ID '5263eab5-358c-4f3a-9d65-b60f2bade089' for connections to the remote server.

MSDeploy.backupSettings development.customer.be/appname

MSDeploy.backupSettings/backupSettings[@path=’development.customer.be/appname']/backupSetting[@turnedOn='False']

MSDeploy.backupSettings/backupSettings[@path='development.customer.be/appname]/backupSetting[@enabled='True']

MSDeploy.backupSettings/backupSettings[@path='development.customer.be/appname']/backupSetting[@numberOfBackups='4']

MSDeploy.backupSettings/backupSettings[@path='development.customer.be/appname']/backupSetting[@continueSyncOnBackupFailure='True']

MSDeploy.backupSettings/backupSettings[@path='development.customer.be/appname']/backupSetting[@excludedProviders='appPoolEnable32Bit; setAcl; appPoolPipeline; createApp; appHostAuthOverride; appPoolNetFx']

There are 2 important things I noticed in the config:

  • The Backup feature is enabled at the site level.
  • The Backup feature is turned off in IIS.

So that explains why we don’t see a backup. We still have to turn on the backup feature.

Turn on backups on the server

Log on to the webserver and execute the following Powershell command:

PS C:\Program Files\iis\Microsoft Web Deploy V3\scripts> TurnOn-Backups -On $true

11:43:53        Information     Turning Backup Feature On.  In order for backups to execute, they still need to be enabled at either the server or site level.

After doing this I did a new deploy. Let’s dump the list of packages again:

msdeploy -verb:dump -source:backupManager="development.customer.be/appname",computerName="serverXX",userName="UserXYZ",password="PasswordXYZ"

This time I got some data back:

Info: Using ID '7b36c65f-fcf1-48e7-a26b-16f8438473ae' for connections to the remote server.

MSDeploy.backupManager development.customer.be/appname

msdeploy_2013_03_15_11_17_34.zip

Wednesday, March 27, 2013

Windows 8: Load html in a webview control

In a Windows 8 application I added a WebView control to load some local HTML files.

I started by setting the source property of the WebView control to the HTML page I embedded into the application:

DisclaimerWebView.Source = new Uri("ms-appx-web:///assets/disclaimer.html");

But when I ran the application, I saw an empty WebView control. So I switched to the  WebView.Navigate method:

DisclaimerWebView.Navigate(new Uri("ms-appx-web:///assets/disclaimer.html"));

No effect… Bedroefde emoticon

After a while I found the reason. I had to explicitly set the Width and the Height of the WebView control. And finally my HTML was loaded.

Tuesday, March 26, 2013

SOA: the first rule of versioning web services

One important element in building a good SOA(Service Oriented Architecture) is creating a good versioning approach. If you fail to get good versioning from the start, It will become really hard to fix it afterwards.

So therefore remember the first rule of versioning web services:

 

“One object in, One object out”

 

What does it mean?

Let’s explain with the following sample. Imagine I created a webservice with the following method:

This is a hard to version service and a really bad example. Why? Because we are using a simple type as input(in this case a guid). This means that in this case we have one object out, but not one object in. If later we have to add a second input parameter, we’ll end up with a breaking change.

A better alternative is to use the following contract:

Now we have one object in, one object out. If we want to send some extra data, we can just add it to the OrderRequest object as an extra property.

Monday, March 25, 2013

Here's why HTML-based apps don't work

I’m currently working on a cross-platform solution using Xamarin.

Today a colleague sent me a link to the following article: Here's why HTML-based apps don't work. In this article Matt Baxter-Reynolds who worked on a number of different projects based on PhoneGap/Apache Cordova shares his experiences.

There is one quote(and the conclusion of the article) that I want to share with you:

“Go native, try Xamarin. But in terms of hybrid: avoid.”

I’m just saying… Glimlach

Friday, March 22, 2013

Where is the Add STS reference option in Visual Studio 2012?

In Visual Studio 2012 the Add STS reference… option is replaced by a completely new tool: The Identity and Access Tool.

The Identity and Access Tool for Visual Studio 2012 enables you to secure your application with claims based identity and accept users from multiple identity providers.

This extension adds a context sensitive project menu entry to easily add identity capabilities to your Web Applications, MVC Applications and WCF Services. This will provide you with capabilities for developing and testing your application with a Local Development STS, connecting to a corporate identity provider like ADFS2 and using the Windows Azure Access Control Service to connect to other identity provides such as LiveID, Google, Yahoo and Facebook. It does this by updating your web.config file with the proper settings to enable the Windows Identity Foundation in .NET 4.5 and adding the necessary configuration for the identity provider you select.

This tool is not available out-of-the-box. So you have to install it from the Extension Manager in Visual Studio:

    • From the menu select TOOLS | Extensions and Updates. . .
    • Click the Online extensions node in the tree view on the left.
    • Search for “Identity and Access Tool” in the search field in the upper right
    • Click the Download button to download and install the package.
    • Click Restart Now to Restart Visual Studio.

    After restarting Visual Studio, you should now see the Identity and Access. . . option if you right-click on your project.

    IdentityAndAccessTool

    Remark: If the option is not there after installing the extension, check if the target framework for your project is set to .NET 4.5.  I first tried it on a .NET 4.0 project and lost a lot of time investigating why the option was not available.

    Thursday, March 21, 2013

    ASP.NET MVC 4: the _references.js file

    When creating a new ASP.NET MVC 4 project, I noticed that a  _references.js file was added to the Scripts folder.

    If we look at the content, I only see some comments. So what is it good for?

    The VS <reference /> Syntax

    The // <reference path=”…” /> allows you to enable IntelliSense in any JavaScript file by including everything defined in the JavaScript located at this path.Visual Studio 2012 will give you IntelliSense for all files that have references in the “_references.js” file. This way you can enable IntelliSense for the JavaScript files you use all the time.

    If you want, you can add your own files too:

    • Go to Tools –> Options.
    • Browse in the Tree view to Text Editor –> JavaScript –> IntelliSense –> References
    • Here you can add other script files containing reference paths

    image

    Wednesday, March 20, 2013

    Add bugs to the task board or backlog pages

    One question I get a lot from customers is how to manage their bugs using Team Foundation Server 2012. Some teams like to track bugs as tasks and other teams track them as backlog items, such as user stories or requirements. If you’re using a Scrum project, bugs are already in your backlog. However, if your team project was created using the Agile, CMMI, or other process template, bugs don't appear on the task board or the backlog pages.

    Figure 1: Manage bugs at the Task board level

    Figure 2: Manage bugs at the Product Backlog level

    The Visual Studio team created a blog post explaining the steps to add bugs to either the task board or the product backlog.

    Tuesday, March 19, 2013

    Windows Azure Service Bus: Unable to use Transport protection with Hybrid mode

    One of the nice features of Windows Azure Service Bus is the ability to expose an internal WCF service through Azure without any extra configuration on the firewall/network level. This means that a user connects to your service through the Azure Service Bus.

    Relay Concepts

    You can even take this one step further and change the relay binding to ‘Hybrid’ mode. This means that the Azure Service Bus tries to ‘upgrade’ the connection to a peer to peer connection between the client and the WCF service without going through the Azure Service Bus anymore. This sounds like a little bit of magic, and it actually is(at least for me).

    Configuring this can be done through the connectionMode property on the binding element:

    • Relayed (default): All communication is relayed through the relay service. The SSL-protected control connection is used to negotiate a relayed end-to-end socket connection that all communication flows through. Once the connection is established the relay service behaves as a socket forwarder proxy relaying a bi-directional byte stream.
    • Hybrid: The initial communication is relayed through the relay service infrastructure while the client/service negotiate a direct socket connection to each other. The coordination of this direct connection is governed by the relay service. The direct socket connection algorithm can establish direct connections between two parties that sit behind opposing firewalls and NAT devices. The algorithm uses only outbound connections for firewall traversal and relies on a mutual port prediction algorithm for NAT traversal. Once a direct connection can be established the relayed connection is automatically upgraded to a direct connection without message or data loss. If the direct connection cannot be established, data will continue to flow through the relay service as usual.

    So let’s enable this functionality  by changing the connectionMode on the RelayBinding to Hybrid:

    However after doing this, the following exception occurred when running the application:

    “Invalid configuration. Unable to use transport protection with Hybrid mode.”

    clip_image002

    This exception is thrown if you try to setup transport security when using hybrid connection mode. The simples solution is to disable transport security which is by default enabled:

    Monday, March 18, 2013

    Mono for Android: Read string resource value from code

    For an Android application we are building, we added some string values to our /resources/values/strings XML file. Mono for Android detects this and generates a strongly typed value in a designer class.

    The only problem is that the generated value is an integer, not the string value itself. So how can we get access to the string resource?

    Friday, March 15, 2013

    TFS 2012 Build error: Multiple identities found matching ‘User Name’.

    One of the issues we encountered after upgrading from TFS 2010 to TFS 2012 is related to the build. What’s particular to our environment is that we have 2 domains(both containing the same users). The goal is to move from one domain to another(and remove the old obsolete domain), but this is taking a little bit longer as expected Glimlach. In the meanwhile we are stuck with 2 domains.

    This already gave us some trouble when upgrading from TFS 2008 to TFS 2010, but now it’s back to haunt us again…

    This time it goes wrong when the build server tries to execute the Associate ChangeSets and related Workitems build step. This step fails with the following error message:

    Exception Message: Multiple identities found matching 'Username'. Please specify one of the following identities:- Username(NEW_DOMAIN\Login)- Username(OLD_DOMAIN\Login) (type MultipleIdentitiesFoundException)Exception Stack Trace:    at System.Activities.Statements.Throw.Execute(CodeActivityContext context)   at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)   at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

    Unfortunately we were not able to find a solution. A colleague filed a bug at Connect, so we’ll see how this will continue…

    Thursday, March 14, 2013

    Visual Studio LightSwitch: maybe it’s time to give it a second chance

    A few weeks ago I went to a presentation about LightSwitch at our local user group. The presentation was great but I wasn’t convinced that LightSwitch was the right tool for me…

    There were some features still missing that I think are critical before I want to use it for my projects. Somehow Microsoft was able to read my mind because with the announcement of Visual Studio 2012 Update 2 CTP 4,  they released an updated preview of the LightSwitch HTML Client containing almost every feature I was looking for.

    Lightswitch

    What’s new?

    • New UI primitives such as command bars, popups, and reusable dialogs.
    • Responsive User Interface to adapt gracefully to different form factors.
    • Deploy your application as a provider-hosted app in addition to auto-hosting.
    • Deploy your app to Sharepoint 2013 on premise(in addition to being able to run your app in Office 365)
    • Localize your app into multiple languages.
    • NuGet Package integration.
    • And many more…

    The official announcement and more details here: http://blogs.msdn.com/b/lightswitch/archive/2013/03/04/announcing-a-new-preview-of-the-lightswitch-html-client.aspx

    You can download the CTP here: Visual Studio 2012 Update 2 CTP 4

    And check out the following tutorials to get started:

    Wednesday, March 13, 2013

    TFS 2012 Test migration: be careful when switching between environments

    For a customer I’m preparing the migration process from TFS 2010 to TFS 2012. To test the migration, we did a test upgrade from TFS 2010 to TFS 2012 on a separate server.

    This allows to test the new behavior in isolation, validate if our customizations still work and hopefully save us some time when doing the production migration.

    One thing we struggled with is that we couldn’t switch back to the old TFS 2010 environment after connecting to the TFS 2012 environment. Same problem when trying to connect to the old build server after connecting to the new one.

    Instead Team Explorer showed a HTTP code 404: Not Found message.

    clip_image002

    The solution for everything: clear the cache.

    The solution is simple. It looks like Visual Studio is caching some information about the TFS servers. Because these servers are almost the same, I guess that Visual Studio mixes up some things.

    To fix it, you have to clear the cache folder located at: C:\Users\userName\AppData\Local\Microsoft\Team Foundation\4.0\Cache

    Afterwards you should be able to connect again…

    Tuesday, March 12, 2013

    Better Unit Testing with Microsoft Fakes guide

    The ALM Rangers did it again. Last week they released a new guide:  Better Unit Testing with Microsoft Fakes. This guidance document provides you with a jump-start for effectively using Microsoft Fakes in your projects.

    Microsoft Fakes makes it easier and faster to create well-isolated unit tests when you do have systems that are “testable,” letting you focus on writing good tests and not on test plumbing. It also enables you to isolate and test code that is not traditionally easy to test, by using a technology called Shims. Shims use runtime interception to let you detour around challenging dependencies and replace them with something you can control. As we have mentioned, being able to create this control variable is imperative when creating high-quality, fast-running unit tests.

    Shims provide a very powerful capability that will let you circumvent all kinds of roadblocks when unit testing your code. As with all powerful tools, there are a number of patterns, techniques and other “gotchas” that can take time to learn.

    Monday, March 11, 2013

    Sharepoint 2013: Help, my user account contains some strange characters

    After upgrading a Sharepoint environment from Sharepoint 2010 to Sharepoint 2013, users started to panic.

    Why? Because some strange characters were added to their account names. To give you an example:

    “Lastname Firstname (i:0#.w|domain\accountname)”

    Did something strange happened during the migration that changed all the accounts? No, this is actually a feature. What you see is the claim information about this user.

    How do you need to decode this claim information?

    • i an identity claim
    • # user logon name
    • . of type string
    • w windows account

    More information can be found here: http://www.wictorwilen.se/Post/How-Claims-encoding-works-in-SharePoint-2010.aspx

    Friday, March 8, 2013

    Enable dynamic compression for an ASP.NET MVC JSON result

    First of all make sure that dynamic compression is enabled and configured in IIS.
    Afterwards you just have to add the following section to your IIS config(located at  %WinDir%\System32\inetsrv\config\applicationHost.config):
     

    Maybe it should work too if you add this to your web.config, but I couldn’t get this working.

    Thursday, March 7, 2013

    Xamarin 2.0: bringing cross-platform development to the next level

    Xamarin brought cross-platform mobile development to the next level. With the announcement of Xamarin 2.0 comes a rebranding of their products, a new IDE called Xamarin Studio, a Visual Studio add-in for iOS development, and the introduction of a component store.

    Xamarin Studio

    Xamarin Studio is the successor of MonoDevelop. It has a new interface and provides some of the functionality familiar to Visual Studio developers: auto-completion, refactoring, syntax highlighting, code tooltips, code navigation, integrated debugger for simulator/emulator or the real device, integration with Git and Subversion. Don’t forget to have a look at ‘the making of’.

    Visual Studio Add-in for iOS development

    Xamarin offered the option to do iOS development before, but you couldn’t use Visual Studio and had to switch to MonoDevelop(which was a great IDE by the way). Now Xamarin fixed this by releasing a Visual Studio add-in for iOS development. This add-in offers good integration with Microsoft’s ecosystem including remote debugging and testing in a simulator on a Mac OS machine(so you still need a Mac OS machine to test your application).

    Component Store

    The last new feature that Xamarin 2.0 introduces is the Component Store. Xamarin has built a framework for creating, sharing and reusing components directly from the IDE increasing the development speed.The store offers ready-to-use mobile themes, Xamarin.Mobile providing an API for accessing common platform features, and much more…

    Have a look at http://components.xamarin.com/.

    Wednesday, March 6, 2013

    Portable HttpClient for .NET Framework and Windows Phone released

    HttpClient is a part of .NET Framework 4.5 and Windows Store apps that provides developers an extremely easy way to connect with services across the internet including REST-based services. But if you wanted to use the same library in Windows Phone 8 or a portable library you were out of luck.

    Last month Microsoft changed this by releasing a Beta of the portable version of HttpClient.

    This release of HttpClient adds support for the following platforms:

    • .NET framework 4.0
    • Windows Phone 7.5 and higher
    • Portable class libraries

    What do I need?

    In order to use this release of HttpClient you need to ensure that you have two things.

    • Visual Studio 2010 (for .NET 4.0 Windows Phone 7.1) or Visual Studio 2012 (required for .NET 4.5, Windows Store and Windows Phone 8).
    • The NuGet package manager version 2.1 or higher.

    To use the HttpClient package, right click on your solution, go to the Manage Nuget Packages dialog, search for Id Microsoft.Net.Http, and make sure “Include Prerelease” is turned on.

    Remark:

    If you are writing a cross platform app targeting .Net 4.0 or the windows phone  and you start using the HttpClient, you probably will get a compile error:

    “Cannot await System.Threading.Task<HttpRequestMessage>”

    This is because .Net 4.0 and Windows Phone 7.5 did not support the async/await keywords.In order to fix this add a reference to the Microsoft.Bcl.Async nuget package, which adds the support for Async and Await in down level platforms.

    Tuesday, March 5, 2013

    Code can change the world

    An inspirational video about software development(and a look at some cool offices too…)

    If you are interested, go have a look at code.org.

    Monday, March 4, 2013

    Windows 8 Unit testing: Include files in your test project

    What can I say? Unit testing Windows 8 applications is a painful experience. It’s hard to apply mocking and some stuff is not easy to discover.

    Last week I created a Windows 8 unit test that required a specific file to be available on the file system. So I added the file to my test project, changed the Build action to content and set Copy to output directory to Copy always.

    But now the hard part what code should I use to read out the file from the file system?

    That's it. Once you found it, it's actually not so difficult.

    Friday, March 1, 2013

    Visual Studio: Reference a different DLL depending on your build configuration

    For a Windows 8 application we are building, we have to deploy versions that connect to different backends. We could have created different branches  but this would result in lots of merges. Instead we decided to go for a provider model combined with conditional compilation symbols. This allows us to easily switch between providers by changing the build configuration.
    This brought us half way there but we had still an issue because we also had to use a different 3th party component depending on the backend. So what we actually want is that when setting the build configuration to QA, the 3thparty.component.QA winmd file was loaded and if we switch to Production the 3thparty.component.Production winmd file was loaded.
    This is perfectly possible by changing the project file and editing the underlying MSBuild settings:
    • Unload the project.
    • Choose Edit project and open it using the XML editor.
    • Find the reference to the component you want to change depending on the build configuration.
    <Reference Include="3thPartyComponent">
     <HintPath>..\packages\3thPartyComponentQA\lib\winrt45\3thparty.component.QA.winmd</HintPath>
    </Reference>

    • Duplicate the reference for each build configuration you want to support.
    <Reference Include="3thPartyComponent">
     <HintPath>..\packages\3thPartyComponentQA\lib\winrt45\3thparty.component.QA.winmd</HintPath>
    </Reference>
    <Reference Include="3thPartyComponent">
     <HintPath>..\packages\3thPartyComponentProduction\lib\winrt45\3thparty.component.Production.winmd</HintPath>
    </Reference>

    • Apply a conditional to the Reference elements.

    <Reference Include="3thPartyComponent" Condition="'$(Configuration)'=='QA'">
     <HintPath>..\packages\3thPartyComponentQA\lib\winrt45\3thparty.component.QA.winmd</HintPath>
    </Reference>
    <Reference Include="3thPartyComponent" Condition="'$(Configuration)'=='Production'">
     <HintPath>..\packages\3thPartyComponentProduction\lib\winrt45\3thparty.component.Production.winmd</HintPath>
    </Reference>