Monday, January 31, 2011

MVVM and the WP7 ApplicationBar

Last week, I spend some time trying to find the best way to use the WP7 ApplicationBar in an MVVM style way.  What makes this hard is that in the current version of the Windows Phone 7 Silverlight framework, it is not possible to attach any command on the ApplicationBarMenuItem and ApplicationBarButton controls.

After trying multiple styles, I choose for the most pragmatic solution(with the risk that the MVVM police will come and arrest me). I simply invoke the command in the ViewModel from the codebehind.

In the XAML I register for the Click event:

<shell:ApplicationBarIconButton Text="Refresh" Click="Refresh_Click" IconUri="/Resources/appbar.refresh.png"/>



And in the code behind I invoke the command:



private void Refresh_Click(object sender, EventArgs e)
{
var vm = DataContext as EventsViewModel;
if (vm != null)
{
vm.RefreshCommand.Execute(null);
}
}


I know that it is less elegant than using attached behaviors, but it works fine.

Sunday, January 30, 2011

Async updates of Windows Forms controls

Derick Bailey published this nice extension method to simplify the invokation of  Windows Forms controls outside the UI thread.

public static class ControlExtensions
{
public static void Do<TControl>(this TControl control, Action<TControl> action)
where TControl: Control
{
if (control.InvokeRequired)
control.Invoke(action, control);
else
action(control);
}
}


It's a simple extension method that allows any UI control to update itself when called from an asynchronous method - whether it's running from a .BeginInvoke() call, a BackgroundWorker, a ThreadPool thread, or any other form of asynchronous call. Simple, clean and useful.



Thanks Derick!

10 jQuery tips to make your site go faster

 

While searching for some best practices about jQuery usage, I stumbled over the following blog post with 10 tips to make your jQuery site go even faster: http://csharptutorial.blogspot.com/2010/12/10-tricks-that-will-make-your-jquery.html.

Saturday, January 29, 2011

TFS 2010: Setting Remaining work to 0

Last week, I got a customer request to update the "Remaining Work" field and set it to 0 when the work item is resolved. Doing this can easily be done by altering the work item type definition. First of all make sure that you have the Team Foundation Server Power Tools installed.

  • Open Visual Studio 2010. Go to Tools –> Process Editor –>Work Item Types  --> Open WIT From Server.
  • Select the Team Project and Work Item Type you want to open. The Work Item Type Editor is loaded.
  • Go to the workflow tab and click on the desired transition. The Workflow Transition window is loaded.

 WorkflowTransition

  • Go to the Fields tab. Add a field reference to "Microsoft.VSTS.Scheduling.RemainingWork"

FieldReference

  • Add a new rule of type "COPY"

SelectARuleType

  • Choose From = "value" and enter value = "0"

Copy

TFS Error while downloading files to workspace: The server returned content type text/html, which is not supported.

Last week, one of my clients reported me the following error while downloading a branch in a new workspace:

C:\Source Control\ProjectName\03 Releases\2.0.3828\ProjectName.Business\Logic\Reservation\Calculations\CalculateDataR1BL.cs: The server returned content type text/html, which is not supported.

After investigation we came to this post and execute the proposed SQL script on the TFS database as shown in the attached screenshot.

image

This problem can happen if you upgraded from TFS 2008/2005. If the sql query returns more than 0 rows, you are indeed affected by the problem. Luckily a hot fix is available(KB Article Number : 2434700 ). Contact Microsoft Support to get a link to the download location.

Friday, January 28, 2011

Caliburn.Micro at VISUG

On Tuesday, February 08, 2011 I’m doing a session about Caliburn.Micro for the Visual Studio User group in Belgium.

You've heard a lot about Model-View-ViewModel (MVVM), but you've struggled to see how it can help you in your day-to-day work. Or, you're experienced at implementing MVVM, but looking for some ways to maximize your investment in this methodology. In this session, we explore Caliburn.Micro(http://caliburnmicro.codeplex.com/), a simple MVVM framework, by iteratively identifying pain points in our UI development and eliminating them with simple solutions. You'll walk away with code, but more importantly with an understanding of how to apply some simple ideas to improve productivity with MVVM in your own projects.

Be there!

Thursday, January 27, 2011

TFS Administration Tool for TFS 2010

After a very long waiting time,  there is finally a new version of the TFS Administration Tool available. You can download it from the TFS Administration Tool project website. This release is the first version of the TFS Administration Tool which is built on top of the Team Foundation Server 2010 object model.

Note: Before installing the TFS Administration Tool 2.1 please make sure that you have removed the previous versions of the tool from your machine and that you either Team Explorer 2010 or Team Foundation Server 2010 installed.

If you don’t know the TFS Administration tool, in short it allows Team Foundation Server administrators to manage user permissions on all three platforms utilized by Team Foundation Server: Team Foundation Server, SharePoint, and SQL Server Reporting Services. The tool also allows administrators to easily copy user permissions among team projects and to easily identify any missing permissions on any of the three platforms.

A must have for all TFS administrators!

Wednesday, January 26, 2011

Azure Durable Message Buffers

Last year at PDC 2010, the Azure AppFabric team made a number of important announcements. One of the improvements they released was a significantly enhanced version of the Azure AppFabric Service Bus Message Buffers feature.[windows_azure[3].jpg]

What’s the difference between the current Message Buffers and the new Durable Message Buffers?

The current version of Message Buffers provide a small in-memory store inside the Azure Service Bus where up to 50 messages no larger than 64KB can be stored for up to ten minutes. Each message can be retrieved by a single receiver. This makes the range of scenario’s where this is useful somewhat limited. The new version of Message Buffers enhance this feature so it could have a much wider appeal. Message Buffers are now durable and look much more like a queuing system. This makes it possible to start using Durable Message Buffers as an alternative to the Azure Queues.

Tuesday, January 25, 2011

WPF: Creating a borderless window

For a new application we are building we want to have a completely different look for the windows in our application. Therefore we wish to eliminate the border to give it a custom look. Doing this in WPF is easy. To get a border-less window, you need to set the following attributes on your Window.

  • WindowStyle="None"
  • AllowsTransparency="True"
  • Background="Transparent"

The WindowStyle attribute normally allows you to set a single border, three-D border, or a Tool Window border. Setting this attribute to None will eliminate the border. The next two attributes, AllowsTransparency and Background work together. You must set AllowsTransparency to True to allow the Background to be set to Transparent.

Monday, January 24, 2011

Windows Phone 7: Setting the start page

By default when you create a Windows Phone 7 application, a start page is created for you. But what if you want to change this later on to a different page? We need a way to specify which page should be used as start page. All that we need now is to change the startpage from MainPage.xaml to newstartpage.xaml .

  • Expand the Properties folder of the WP7 C# Project and Open the WMAppManifest.xml

WMAppManifest

  • This file keeps track of things that belongs to the Application . The important property here is the DefaultTask.
  • Change the NavigationPage to the page you want to use as start page .

WMPAppManifestContent

Sunday, January 23, 2011

Windows Phone 7: Simplify URL typing

When the user places the focus on to the textbox, in the Windows Phone 7, the default keyboard / onscreen keyboard will pop up for the user to touch and type the characters to the textbox. It is also important that the keyboard can be customized depending on the input the user will be typing or the data type the textbox is associated with.

For an application we are building the user has to specify a URL. By specifying an input scope, we can change the layout of the Keyboard.  This will help the end user to easily type the required characters even faster.

Setting the Input Scope is very simple and is demonstrated below.The sample Application contains a simple textbox (textBox1) with a title.

When the focus comes to the textbox, the default onscreen keyboard will be displayed as shown below.

image

If we want to change this to speed up url writing, add an event handler to the page loaded event and insert the following code:

InputScope Keyboard = new InputScope(); 
InputScopeName ScopeName = new InputScopeName(); 
ScopeName.NameValue = InputScopeNameValue.Url; 
Keyboard.Names.Add(ScopeName); 
textBox1.InputScope = Keyboard;

If we run the application again and click on the Textbox, the keyboard changes as displayed below.

image

Saturday, January 22, 2011

Windows Phone 7: Detecting the WP7 Theme

The Windows Phone 7 comes with two background color modes dark or light. The easiest way to identify the Theme that the user has choosen in the device can be found via the Application Resources .

In the Development Environment , you can find the file ThemeResources.xaml in the path
C:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Design

The easiest way to find if the Dark or Light Background is visible is again by using the Resources string PhoneLightThemeVisibility or PhoneDarkThemeVisibility which will give you information if visible or collapsed . You can encapsulate this logic in your own class and use it throughout your application.

   1:   public class Settings
   2:      {
   3:          public static Settings Instance = new Settings();
   4:   
   5:          private Settings()
   6:          {
   7:          }
   8:   
   9:          public Theme CurrentTheme 
  10:          {
  11:              get { return (Visibility)Application.Current.Resources["PhoneLightThemeVisibility"] == Visibility.Visible? Theme.Light: Theme.Dark ; } 
  12:          }
  13:      }
  14:   
  15:      public enum Theme
  16:      { 
  17:          Light,
  18:          Dark
  19:      }

Friday, January 21, 2011

Windows Phone 7: Setting the Tile image

On a Windows Phone 7 people can pin your application to their start screen. To pin an app, you hold down until you get the menu below, then you pin it to the start screen.

image

After you do this, you’ll see a big icon box with your application name.

image

The icon that is shown in the Tile can be set in the project’s properties page…

image

But although I changed the Background image to another png, it didn’t show up inside the Tile. I found out that I didn’t see my image because I had set the Build Action for my PNG file to Resource instead of Content. Adding it defaults to Resource, but for the purposes of the Pin-To-Start tile image, you just need to switch it to Content instead.

Still strange that I was able to pick it from the Background image list…

Thursday, January 20, 2011

Windows Phone 7: Detect device type

The Windows Phone 7 Emulator is a great way to test your applications before deploying them. However there are obvious limitations, such as working against the GPS system where the emulator just can’t quite cut it. In those situations it is common to create some sort of simulation to mimic the desired behavior.

But once you have deployed your application to a real device you do not want your simulation routines to execute. Fortunately you can check for the DeviceType and avoid calling any emulator specific code you may have embedded.

Checking For the WP7 Device Type

The System.Devices.Environment.DeviceType property returns either DeviceType.Device or DeviceType.Emulator indicating what platform the application is running. Notice that reading the Microsoft.Devices.Environment.DeviceType property generates garbage, causing garbage collections when you don't want them.  Therefore it’s better to call it once at the start of your app and save the value.

Here is a simple example how you can do this:

   1:  public class Settings
   2:     {
   3:         public static Settings Instance = new Settings();
   4:   
   5:         private Settings()
   6:         {
   7:             IsRunningInEmulator = CheckIfRunningInEmulator();
   8:         }
   9:   
  10:         public bool IsRunningInEmulator { get; private set; }
  11:   
  12:         private bool CheckIfRunningInEmulator()
  13:         {
  14:             return Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator;
  15:         }
  16:     }
  17:   
  18:   

So instead of calling the DeviceType property each time you needed it you would call the IsEmulator property which would rely on the _isEmulator variable after the first call.

Wednesday, January 19, 2011

Razor Syntax Quick Reference

With the release of ASP.NET MVC 3 and WebMatrix 1.0 you get the new Razor syntax for your views. Although Intellisense helps you a lot, some extra guidance for the Razor syntax can be useful. It turns out, there is a pretty good guide about Razor available, but it’s focused on covering the basics of web programming using Razor and inline pages and not just the Razor syntax. If you are looking for a concise quick reference about the Razor syntax, check out Phil Haack’s blog.

Tuesday, January 18, 2011

Icons for your Windows Phone 7 app

Looking for some nice icons to use inside your Windows Phone 7 application?

First have a look  at the Windows Phone 7 icon pack. This package contains a set of 64 app bar icons that you can use when developing applications for Windows Phone. In addition to the 64 icons in PNG format (32 dark and 32 light), this package also contains vector versions that can be easily imported into Microsoft Expression Blend.

UPDATE: The Icon Pack is now part of Expressions Blend for Windows Phone. When you are working with the application bar and add items you can change the icon used using a drop down in Expressions Blend for Windows Phone. When you select an icon it is automatically added to your project. If you want to get to the icons to work with them yourself you can find them on your drive in C:\Program Files\Microsoft SDKs\Windows phone\v7.0\Icons.

appbar.feature.camera.rest appbar.feature.email.rest appbar.feature.search.rest appbar.feature.settings.rest appbar.feature.video.rest appbar.folder.rest appbar.minus.rest appbar.new.rest appbar.next.rest appbar.questionmark.rest appbar.refresh.rest appbar.save.rest appbar.share.rest appbar.stop.rest appbar.sync.rest appbar.transport.ff.rest appbar.transport.pause.rest appbar.transport.play.rest appbar.transport.rew.rest appbar.upload.rest appbar.add.rest appbar.back.rest appbar.basecircle.rest appbar.cancel.rest appbar.check.rest appbar.close.rest appbar.delete.rest appbar.download.rest appbar.edit.rest appbar.favs.addto.rest appbar.favs.rest.

Another option is this package created by  Bil Simber.  It contains 502 Metro style icons in PNG, XAML and the original SVG format along with a couple of sample projects so you can see them in action.

500_icons_wpf

Monday, January 17, 2011

Error while deploying to Windows Azure Devevelopment Fabric

At a customer, after installing the Windows Azure SDK version 1.3 , when we tried to deploy their app on the development fabric, Visual Studio throws us the following exception.

System.ServiceModel.CommunicationObjectFaultedException was unhandled

  Message=The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication because it is in the Faulted state.

  Source=mscorlib

  StackTrace:

    Server stack trace:

       at System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan timeout)

    Exception rethrown at [0]:

       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)

       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)

       at System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)

       at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Close(TimeSpan timeout)

       at Microsoft.WindowsAzure.Hosts.WaIISHost.Program.Main(String[] args)

We tried a lot of stuff to get it working. In the end we recreated a new solution from scratch to determine what could be the cause of this issue. Of course everything worked. By comparing the 2 solutions we discovered that our newly created solution was targeting the .NET Framework 4.0 while our existing solution was targeting the .NET Framework 3.5. Changing the target framework from .NET 3.5 to .NET 4.0 solved the problem.

UPDATE We followed some tips in the comments and discovered the root cause of the issue. Because we were using TFS source control the web.config was changed to readonly. Removing the readonly bits solved the problem. I guess that by changing the target framework the readonly attribute was removed by Visual Studio itself.

Sunday, January 16, 2011

Bug in WP7 Training kit

Last week I lost a lot of time while implementing push notifications for my Windows Phone 7 app(more about it soon!). I implemented the push notifications similar to thearrangement that Microsoft has set up in the WP7 training kit. When I launch the app and then exit the app to go back to the home screen, I am able to successfully send a toast notification.

However, when I send the same exact shell toast notification to my application while the application is running in the foreground, I get an error complaining that there is an invalid character for the root XML node. I found out there is an error in the NotificationSenderUtility that comes with the WP7 push notification sample in the training kit to send the notifications.

Anyway the solution is simple, replace the PrepareToastPayLoad message inside the NotificationSenderUtility with this code:

   1:  private byte[] PrepareToastPayload(string text1, string text2)
   2:          {
   3:              MemoryStream stream = new MemoryStream();
   4:              XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, Encoding = new UTF8Encoding(false) };
   5:              XmlWriter writer = XmlWriter.Create(stream, settings);
   6:              writer.WriteStartDocument();
   7:              writer.WriteStartElement("wp", "Notification", "WPNotification");
   8:              writer.WriteStartElement("wp", "Toast", "WPNotification");
   9:              
  10:              writer.WriteStartElement("wp", "Text1", "WPNotification");
  11:              writer.WriteValue(text1);
  12:              writer.WriteEndElement();
  13:              
  14:              writer.WriteStartElement("wp", "Text2", "WPNotification");
  15:              writer.WriteValue(text2);
  16:              writer.WriteEndElement();
  17:   
  18:              writer.WriteEndElement();
  19:              writer.WriteEndElement();
  20:              writer.WriteEndDocument();
  21:              writer.Close();
  22:   
  23:              byte[] payload = stream.ToArray();
  24:              return payload;
  25:          }

Saturday, January 15, 2011

TF84032: Team Foundation could not insert the work item list.

Last week I upgraded my Office 2007 installation to Office 2010. After the installation was complete, the Team Foundation Server integration started failing. Everytime I tried to open a work item list in Excel, the following error message was returned:

clip_image002

If I tried to open Excel from inside Visual Studio, another error was returned:

image

On the Internet the following possible solutions were mentioned:

  • Repairing the  Visual Studio Tools for Office Runtime. Didn’t help for me.
  • Repairing the Microsoft Office 2010 installation. Didn’t help either
  • Re-registering the TFSOfficeAdd-in.dll (regsvr32 "C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PrivateAssemblies\TFSOfficeAdd-in.dll")

Then I found some information on the MSDN forums about how to get extra tracing info:

1. Copy the following contents to a config file and name it as Excel.Exe.Config (for TFS Excel Add-In) or WinProj.exe.config (for TFS Project Add-in)

<?xml version="1.0"?>

<configuration>

<system.diagnostics>

    <switches>

<add name="General" value="4" />

</switches>

<trace autoflush="true" indentsize="4" />

</system.diagnostics>

</configuration>

2. Copy this config file to the folder where Excel.exe/WinProj.exe is installed (Program Files\Microsoft Office\Office14) . On Vista if UAC is turned on then you won't be able to save a file under Program Files. So save this file under some other folder (say %temp%) and copy this file to Office install directory under Program Files

3. Close and re-launch Excel or WinProj

4. Re-try your scenario. For Excel trace information will be added to %temp%\tfs_msexcel.log and for MSProject it will added to %temp%\tfs_msproject.log

This returned the following information:


[Error, PID 5032, TID 1156, 10:08:16.248] Exception:  {
Exception Message: Error HRESULT E_FAIL has been returned from a call to a COM component. (type COMException)

Exception Stack Trace:    at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
   at Microsoft.TeamFoundation.WorkItemTracking.Client.DataStore.MetadataProvider.get_ConstLookupName()
   at Microsoft.TeamFoundation.WorkItemTracking.Client.DataStore.MetadataProvider.FindConstant(String name, Int32& id)
   at Microsoft.TeamFoundation.WorkItemTracking.Client.Provision.WitExporter.get_GlobalLists()
   at Microsoft.TeamFoundation.WorkItemTracking.Client.Provision.WitExporter.ExportGlobalLists()
   at Microsoft.TeamFoundation.WorkItemTracking.Client.Provision.WitExporter.Export()
   at Microsoft.TeamFoundation.WorkItemTracking.Client.Provision.ProvisionClass.ExportWorkItemType(Int32 projectId, Int32 typeId, Boolean withGlobalListsFlag)
   at Microsoft.TeamFoundation.OfficeIntegration.Client.Common.OfficeProjectContext.CalculateHashCode()
   at Microsoft.TeamFoundation.OfficeIntegration.Client.Common.OfficeProjectContext.Initialize()
   at Microsoft.TeamFoundation.OfficeIntegration.Client.Common.OfficeProjectContext..ctor(NamespaceData namespaceData, String teamProjectName, String projectLocation)
   at Microsoft.TeamFoundation.OfficeIntegration.Client.ExcelAddIn.InsertListObject()
   at Microsoft.TeamFoundation.OfficeIntegration.Client.ExcelCommands.NewWorkItemListCommand_Click_Internal()

}

Didn’t know what to do with that, so as a last resort I re-installed Team Explorer 2010 and this solved the issues. Finally!

Friday, January 14, 2011

Writing a repository class

Persistence has been a hot topic in software development for a long time. The main problem is that the most popular approach for software development these days, Object-Orientation, doesn’t really map easily to efficient external storage systems like relational or even noSQL databases.

The technical limitations were mostly solved with some object mapping tools(ORM) like NHibernate or Entity Framework that make persisting and querying objects a breeze for most scenarios. The problem then became how do we integrate the act of persisting and retrieving objects with our Domain Model and, more important, our Ubiquitous Language.

A good way to integrate persistence needs and the Ubiquitous Language is using what is known as Repositories. In his Domain Driven Design book, Eric Evans defines the Repository pattern as “A mechanism for encapsulating storage, retrieval, and search behaviour which emulates a collection of objects”.

Naming as a solution

The concept of a Repository as a list of objects is not too hard to understand but it is very common for those classes to end up with methods that are not related to lists at all. A lot of repository implementations I have written before suffered this problem. Until I found this blog post by Phil Cal├žado. He states hat the best way to make people remember that Repositories are not DAO-like classes starts with how you name them.

Instead of the more common naming style displayed below:

   1:  class OrderRepository {
   2:     List<Order> GetOrdersFor(Account account){...}
   3:  }

You should use:

   1:  class AllOrders {
   2:     List<Order> BelongingTo(Account account){...}
   3:  }

At first I find it strange that such a small change will make any difference but it really helps a lot. As an example, let’s look at two repositories that contain methods that don’t belong to them. Which one do you think it’s easier to identify as problematic?

   1:  //classic naming style
   2:  class UserRepository{
   3:   User RetrieveUserByLogin(String login){...}
   4:   void SubmitOrder(Order order){...}
   5:  }
   6:   
   7:  //client code
   8:  User u = userRepository.RetrieveUserByLogin(“billgates”);
   9:  userRepository.SubmitOrder(new Order()); 
  10:   
  11:  //new naming style
  12:  class AllUsers{
  13:   User WithLogin(String login){...}
  14:   void SubmitOrder(Order order){...}
  15:  }
  16:   
  17:  //client code
  18:  User u = allusers.WithLogin(“billgates”);
  19:  allusers.SubmitOrder(new Order());

Keep in mind that the language you use does impact how you think (Sapir-Whorf works for programming). Methods that start with retrieve, list of get are often bad smells.

Thursday, January 13, 2011

Effective Windows PowerShell free ebook

A late Christmas gift for everyone,  Keith Hill has turned a set of blog posts into an 61 pages long PowerShell ebook.

Download your own copy here.

 

Table of content:

  • Introduction
  • Item 1: Four Cmdlets that are the Keys to Discovery within PowerShell
    • Key #1: Get-Command
    • #2: Get-Help
    • Key #3: Get-Member
    • Key #4: Get-PSDrive
    • PowerShell 2.0 Update
  • Item 2: Understanding Output
    • Output is Always a .NET Object
    • Function Output Consists of Everything That Isn't Captured
    • Other Types of Output That Can't Be Captured
  • Item 3: Know What Objects Are Flowing Down the Pipeline
  • Item 4: Output Cardinality - Scalars, Collections and Empty Sets - Oh My!
    • Working with Scalars
    • Working with Collections
    • Working with Empty Sets
  • Item 5: Use the Objects, Luke. Use the Objects!
  • Item 6: Know Your Output Formatters
  • Item 7: Understanding PowerShell Parsing Modes
  • Item 8: Understanding ByPropertyName Pipeline Bound Parameters
  • Item 9: Understanding ByValue Pipeline Bound Parameters
  • Item 10: Error Handling
    • Terminating Errors
    • Non-terminating Errors
    • Error Variables
    • Working with Non-Terminating Errors
    • Handling Terminating Errors
    • Trap Statement
    • Try / Catch / Finally
  • Item 11: Regular Expressions - One of the Power Tools in PowerShell
    • PowerShell 2.0 Update
  • Item 12: Comparing Arrays
  • Item 13: Use Set-PSDebug -Strict In Your Scripts – Religiously
    • PowerShell 2.0 Update
  • Item 14: Commenting Out Lines in a Script File
    • PowerShell 2.0 Update
  • Item 15: Using the Output Field Separator Variable $OFS