Archive for category Development

Using WCF without configuration files

I have recently published new project on GitHub, WcfWithoutConfigFile. This post is intended as a ‘readme’ file for this repository.

It’s just a collection of simple projects that I’ve put together when a coworker asked me to show how he can use WCF without configuration files. He got feed up working with XML in web.config and wanted a cleaner and more understandable way to configure Windows Communication Foundation.

What’s in:

  • How to use WCF in your unit tests (WcfWithoutConfigFile.Tests project). Sometimes you want to get your code tested at service boundaries and you want to involve also WCF. It contains, among a simple unit test, a base class for your tests so the test cases are clean and don’t contain plumbing code.
  • Hosting WCF services in IIS (WcfWithoutConfigFile.WebHost project). Defining the service in .svc files and all required infrastructure to instantiate the service via code-only configuration.
  • My favorite – hosting WCF service in IIS using Castle’s WcfIntegration facility  (WcfWithoutConfigFile.WebHost.Castle project). It leverages Castle Windsor container and WcfFacility to easily host/run/consume your WCF services. It also configures the service to use Windows authentication and shows how to retrieve client’s WindowsIdentity in the service. There is also a client project, WcfWithoutConfigFile.WebHost.Castle-Client that connects to service and does some operations.

WcfWithoutConfigFile.WebHost.Castle requires some configuration to get it working properly. Be sure to:

  • Run it in IIS Express
  • Enable Windows Authentication in project properties

1 Comment

The Life After Silverlight 5

There is a lot of panic in Microsoft eco-system caused by some rumors that Silverlight 5 will be the last of the family. Developers are crying about skills being buried and managers fearing about the future of in-house enterprise-grade projects.

And everyone is guessing what will be Microsoft pushing in the segment currently occupied by Silverlight. Now we have two available options, the new guy in the block – the HTML 5, and the good old and trusty WPF. Won’t mention Windows 8 here as it’s way to the Enterprise is too long to be considered as an option.

So, everyone is watching the next move of Microsoft as there is not a clear winner – HTML 5 is too young to be considered seriously and WPF is too old to be considered as a long-time investment. When Silverlight was a competitor the choice was rather easy, now picture is much more blurred.

In my view

XAML & .NET will stay with us. Will it be WPF, Metro or anything MS will roll out for Desktop and LOB applications it will be based on those two pillars. At least for 7-10 years we’re assured.

I’ll make few guesses, what MS’s steps will be after Silverlight end will be announced (it will be interesting to read it in a year or two):

  • A promise that Silverlight 5 will be supported for next 3-4 years
  • A tool for a relatively easy migration from Silverlight to WPF (and/or Windows 8 programming model) will be available
  • Newer versions of WPF will promote features previously hyped as Silverlight’s exclusives (in-browser apps, sandboxing, web deployment & updates and others) minus the ability to run in browsers on various platforms.

As for companies struggling with the choice right now (and it will probably true for near future), you’ll have to decide:

  • Interaction and Data intensive applications, Rich User Experience, Resource Intensive application, deep OS integration – embrace the WPF and be happy (if you don’t mind to lock yourself to MS and Windows).
  • Platform independent, high user base, moderately interactive UIs, presentation and manipulation of small amounts of data – your best bet is the Web: HTML5, CSS3 and JavaScript will be your tools.

And if you still struggle with the choice the best thing you can do next is to look at your current development team. If they are more experienced and efficient with Web technologies you’re set. If they are mostly Desktop specialists then you’d want to explore their productivity to the max and get the release date closer. You’re sorted.

And the last word: don’t be a mono-disciplinary developer. Don’t lock yourself exclusively in Desktop or Web, Microsoft or LAMP or whatever. The day you’ll fail to pick, learn and use efficiently a new tool/framework will mean your career as a Professional Software Developer is done. Be open. Look around, there are so many amazing things in Software Development industry. Just pick something new and learn. It will be one of the best investments you can do in your future. You can do it right now…

Leave a Comment

Cultural differences…

Today I’ve been helping a coworker to bootstrap new project. Nothing fancy: ASP.NET site hosting WCF services, few POCOs and Entity Framework in Code First mode to rule persist them all.

Interesting moment came when he wanted to see if his service actually works. He quickly created another project (Windows Forms) to try connect to newly created service. When I’ve seen that I’ve suggested that a unit test project would be easier and more useful, he preferred to go his route and added buttons, large text block and some plumbing code to take service’s response to the screen.

I’m not blaming here (as he is rather new to .NET platform), but his approach has few disadvantages versus verifying a service using unit tests:

  • it’s slower to create a minimally meaningful solution: a crappy screen with a button “connect” and large text box to see results? I’d prefer a test with an assertion and may be some console output
  • it’s slower to analyze results: you have to scan the screen to see/analyze replies. I’d prefer that a test assertion would take care of that.
  • it’s error prone: you have to rely on human input to test it. I’d prefer an automated approach.
  • it’s not repeatable nor scalable: what if you have second service? 10 methods in service?. I’d create new test fixture and refactor existing code, not UI.

… lot’s of things that are wrong with this approach.

Even if it’s a short living spike, new project, new feature – whatever needs a proof of code in working state – I’d prefer to write a test for it. And I’m not talking here about rigorous Test-Driven-Development approach. It’s more like acceptance testing at service or component boundaries, only to be sure that it works as expected. And creating an UI just to see that a service works – it sounds wrong to me. But those are “cultural differences”, I think…

PS: By “cultural differences” I mean past experience, habits, education, professional environment and so on…

Leave a Comment

How to make Caliburn.Micro and Silverlight resources in MergedDictionaries play nicely together

I’ve fixed an error in our codebase that prevented Caliburn’s bootstrapper and application resources to live happily together. That was manifesting like warnings in xaml about missing resources and styles, no right styles in Visual Studio designer and so on.

Now, to reproduce the problem we have to follow Caliburn’s guidelines then make few changes:

  • Create new Silverlight 4 application
  • Add Caliburn.Micro NuGet package
  • Configure your application to bootstrap Caliburn
  • Add new Resource Dictionary to host your common styles/brushes/whatever
  • Include your dictionary in MergedDictionaries section
  • Add a fancy color brush and use it in ShellView.xaml by referencing it as a static resource
  • Build your app

Your application will compile and run fine. However, you can spot few issues with your code:

  • ShellView.xaml:
    • Xaml editor displaying warning: “The resource could not be resolved”
    • VS Designer will not use your resource on design surface
  • App.xaml
    • Xaml editor displaying warning: “The designer does not support loading dictionaries that mix ‘ResourceDictionary’ items without a key and other items in the same collection. Please ensure that the ‘Resources’ property does not contain ‘ResourceDictionary’ items without a key, or that the ‘ResourceDictionary’ item is the only element in the collection.”

To solve this problem you have to modify your App.xaml.

The original App.xaml fragment, as by following recommendations:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/Generic.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
        <local:AppBootstrapper x:Key="bootstrapper" />
    </Application.Resources>

Now, the corrected version that removes all issues I’ve described earlier:

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/Generic.xaml" />
                <ResourceDictionary>
                    <local:AppBootstrapper x:Key="bootstrapper" />
                </ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

Actually, this fragment is the recommended way of instantiating boostrapper for WPF version of Caliburn.Micro. Why it isn’t recommended also for Silverlight? I don’t know. For our rather large project I haven’t seen any downgrades and issues using this approach. Just few annoying bugs were gone…

1 Comment

Me developer–“I’m done”; me designer–“wait a minute…”

As most of developers working in a small teams or projects I have to work on UI. Should it be a new screen, complete feature with some UI interactions or just a fix of some font/alignment/style issues.

When you’re in “developer mode” criteria for “done” is more or less precise: tests are green, code is OK and metrics (if you have some) are acceptable.

Then I have to do some UI work and when I wear my Designer hat it gets difficult to define “done” criteria. We can easily appreciate “functional” quality of one particular screen. But it’s Design and Usability values are more difficult to formalize. You can check some UI Guidelines, you can show your work to a stakeholder or client. They both will say it’s OK. Then you’re improving it by grouping better screen’s content. They again say “it’s OK”. You’re checking alignments, highlight frequently used commands and do subtle color changes to application’s color set. And again, “it’s OK”.

Is it better than before? Definitely. Is it done? Well … If you’re at your “it’s good enough” point, you probably will stop. Until next time…

To some degree, this tendency towards perfection it’s applicable to development too. A developer can (almost) infinitely polish, optimize & refactor existing code. The code will be better. Will it be observable by final user? Less likely (unless it’s a performance issue). And this is the difference with designer’s work: any change will potentially be appreciated by end-user.

That’s why I think that impact of Design and Usability on any software product is more important that it’s internal beauty.

Leave a Comment

mGitHub Sample Application. Using Caliburn.Micro to build Windows Phone 7 applications

* mGitHub.SampleApp on GitHub

** mGitHub – the real app – is available in Marketplace

The story

I’ve been very excited when Microsoft announced a new & shiny mobile platform, the Windows Phone 7. Mostly because it gave me the chance to explore new things using very familiar tools: Visual Studio 2010, C# and Silverlight. I never had enough time to start digging in this area. When I’ve read that Rob Eisenberg announced a Caliburn.Micro contest and having lost the passion for doing my job at company I’m working now, I’ve decided to participate.

I’ve decided to go with an interesting idea – writing a WP7 app to work with GitHub. Mainly because I’m sure that I will use such app myself. GitHub is an awesome service that lets you host and collaborate on your projects freely once they are open source or if you want private projects you can have it too for a fee. I like idea and this sample application so much, the whole development process went so smooth and easy so that I’ve decided, along with participation in CM contest and publishing sources of my sample app on GitHub, to continue developing it by adding more features to offer a complete and user friendly application to work with GitHub (later about this).

The app

mGitHub.SampleApp allows to browse few preselected projects and repositories on GitHub. You can see user/repository details, navigate trough user’s own repositories, watched repositories, view contributors and so on…

The use of Caliburn.Micro, which is (not only) a MVVM framework, implies that application is View Model driven. Main screen is baked by a view model, then everything else – application flow, user interactions, service calls are done within View Model classes (with few small inclusions of WP7 navigation model, view based).

WP7 controls like Panorama and Pivot were also used with MVVM in mind. For example, here is the code for main View Model that is serving a Panorama-based view:

public class MainPageViewModel : Screen {
    public MainPageViewModel(MostViewedViewModel mostViewed,
                             FavoritesViewModel favorites,
                             AboutViewModel about)
    {
        MostViewed = mostViewed;
        Favorites = favorites;
        About = about;
    }

    public FavoritesViewModel Favorites { get; protected set; }
    public MostViewedViewModel MostViewed { get; protected set; }
    public AboutViewModel About { get; protected set; }
}

So, here we’re just injecting our View Models for individual Panorama pages in MainPageViewModel and then SimpleContainer takes care to provide required instances. Since in a Panorama control all pages are visible (active), we’re using a simple Screen (from CM) as our base class for our VM. Then, this is how the panorama view is defined:

        <controls:Panorama Title="mGitHub sample app "> <controls:Panorama.Background> <ImageBrush ImageSource="PanoramaBackground.jpg"/> </controls:Panorama.Background> <controls:PanoramaItem x:Name="Favorites" Header="my favorites" /> <controls:PanoramaItem x:Name="MostViewed" Header="interesting" /> <controls:PanoramaItem x:Name="About" Header="about" /> </controls:Panorama> 

It’s nice and clean, with very good separation of concerns: each panorama page has it’s own View and a corresponding View Model. The work to glue it together is done by Caliburn.

The Pivot is a bit different. This control is basically a well known TabControl, it has headers and only one item is active at a time. For a PivotViewModel we’ll use a Conductor class with one active item:

[SurviveTombstone]
public class PivotViewModel : Conductor<IScreen>.Collection.OneActive {
}

Then the two application Pivots, UserPivotViewModel and RepositoryPivotViewModel will just ask from container the view models of individual pages and add them to Items collection of Conductor class:

[SurviveTombstone]
public class UserPivotViewModel : PivotViewModel {
    private readonly UserDetailsViewModel details;
    private readonly UserRepositoriesViewModel repositoriesViewModel;
    private readonly UserWatchingViewModel watchingViewModel;

    public UserPivotViewModel(UserDetailsViewModel details,
                              UserRepositoriesViewModel repositoriesViewModel,
                              UserWatchingViewModel watchingViewModel)
    {
        this.details = details;
        this.repositoriesViewModel = repositoriesViewModel;
        this.watchingViewModel = watchingViewModel;
    }
    protected override void OnInitialize()
    {
        base.OnInitialize();

        Items.Add(details);
        Items.Add(repositoriesViewModel);
        Items.Add(watchingViewModel);

        ActivateItem(details);
    }

The view, again, is very simple, grace of Caliburn.Micro magic:

        <controls:Pivot x:Name="Items" Title="{Binding PivotTitle}" SelectedItem="{Binding ActiveItem, Mode=TwoWay}"> <controls:Pivot.HeaderTemplate> <DataTemplate> <TextBlock Text="{Binding DisplayName}" /> </DataTemplate> </controls:Pivot.HeaderTemplate> </controls:Pivot> 

That’s why I enjoy using this framework, it makes some development tasks extremely simple.

Also, application make use of INavigationService,  wrapper API for Launchers/Choosers and is aware of Thombstoning. I tried to keepcode small enough to be easily followed and read, so it will not be too hard to find those places in project’s source code…

Another (probably interesting) piece of code in this project is communication with GitHub using their API. It’s not exactly the IGitHubHost service that I want to highlight, it’s pretty trivial. Take a look at two wrappers around RequestProcessor class, both added in order to improve User Experience when working with mGitHub.SampleApp on the phone:

  • ProgressAwareRequestProcessor – will show a view with PerformanceProgressBar during any remote call
  • CachingRequestProcessor – providing a extremely simplistic data cache, storing requests and their results

These wrappers are registered in container and View Models even don’t know about their abilities, for them it’s just issuing a call and displaying a result. Separation of concerns is always good principle to follow…

Screenshots

Few screenshots, to get the sense of how UI looks like:

12

34

 

Final notes

This application surely contains bugs, it probably has few strange design decisions and graphics are done by professional developer (me). But it works. It serves it’s main purpose to show how you can write an application for Windows Phone 7 using Caliburn.Micro. And I had a lot of fun working on it…

I’ll surely improve this sample, fix reported bugs and will listen carefully to improvement ideas. So, any feedback is welcome.

But in the meantime, I’m doing everything possible to release a real application to Marketplace that will be called mGitHub and will offer essentially improved experience and more features. So, if you like the idea, if you like GitHub and will most likely use the app on your phone, I would be glad to hear from you. Next time when I’ll be planning features your feedback will be considered.

This application weren’t tested on a real phone. I’m counting the hours until my hands will get the ordered Samsung Omnia 7 and I’ll be testing this app on real hardware. If everything goes well, expect yearly next week a feedback (and probably fixes & improvements) after using the app on WP7 device.

Code of this application is licensed under MIT license and available on GitHub.

Credits

Thanks to:

Special thanks to:

  • my friend Dumitru Cantemir for helping me with some code.
  • my daughter, for letting her dad working on this app. Even if sometimes it was …

DadAtWork

3 Comments

Perceived performance

I’m watching a recording of Windows Phone Design Days, it’s the part about “perceived performance” with Jaime Rodriguez. He put up a nice table with response times and recommended visual feedback. I’ve seen these recommendations before. I’ve talked about these recommendations with my team. I’m insisting applying them every time when I see in out apps that an action has no visual response within one second after triggering it.

Even if it’s talking in context of User Experience on Windows Phone, I think these numbers are a formal guidance for good user experience on every device, modern gadget or software application.

I’ll make a copy of this table here, just to keep it in a handy place for further reference. It’s so well worth keeping it…

system response time duration recommended feedback
instantaneous response bellow 100 milliseconds built in common controls
immediate response between  500 milliseconds and 1 second built in common controls
vers short wait 2 seconds or less built in common controls
short wait 2 to 5 seconds progress bars
moderate wait 5 to 10 seconds progress bar with details like percentage completition or time remaining
long wait 10 seconds or greater progress bar with details of sub steps. Allow user to move to other tasks
continuous feedback long process progress bar with details of sub steps. Allow user to move to other tasks

Read, remember, apply!

1 Comment

Visual composition and extensibility are done right…

… when in order to look at some debug data in runtime you’re not writing log messages, not inspecting with debugger your data, not dumping structures to files. Instead, you’re taking the most confortable route, which is write a Widget and show it in the Dashboard of your app. Oh my, that was really fun to discover.

How to cook it – Silverlight, Castle Winsor and Caliburn Micro. Add a good part of ‘conventions over configuration’. Mixing together you’re implementing the Concept – Dashboard and Widgets. After internal mechanics are done (and tested), adding new Features (concrete Widgets) are piece of cake.

Additional reading  – Ayende about Concepts and Features.

Leave a Comment

Houston, we have a problem. Unit tests in Silverlight…

Going deeply into Silverlight development I’ve hit a bump that have destabilized me.

I’m at the point where I want to begin write unit tests for a Silverlight app.

Until this moment, NUnit, Resharper and TeamCity were working formidably well in this regard, covering all my needs: I’ve been productive writing tests and tools were at the hand to pick them up & run. That’s when targeting .NET Framework.

If we’re back to Silverlight, major unit test frameworks are not ready. Silverlight support is either announced or present in some experimental state. And if even I’ll found a way to write my tests, Resharper and TeamCity will not be able to run them automatically, requiring manual tweaks or installing additional things.

Looking deeper for a solution…

2 Comments

How to reference platform specific (x86/x64) assemblies in Visual Studio projects

Let’s say you have a third party library that you want to reference from your project. By default platform target in Visual Studio is “Any CPU”. But the library is compiled for specific target – x86 or x64. When you’re working in a team, have a build server and all of them is in different platforms you’ll start to have issues. Like, project with an x64 referenced assembly working ok on your x64 machine and failing on x86 computers and so on.

For us it was the “System.Data.SQLite” – the ADO.NET provider for SQLite. It is provided compiled separately for 32 and 64 bit systems. It was not easy to figure out how to manage references to SQLite provider without making too much changes in our projects and build scripts.

I’ve found an elegant solution for it: manually modifying project files that are using it to add a conditional elements to <Project> node. Look at this code:

  <Choose>
    <When Condition=”$(PROCESSOR_ARCHITECTURE) == ‘AMD64′ Or $(PROCESSOR_ARCHITEW6432) == ‘AMD64′”>
      <ItemGroup>
        <Reference Include=”System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64″>
          <SpecificVersion>False</SpecificVersion>
          <HintPath>..\Lib\x64\System.Data.SQLite.DLL</HintPath>
        </Reference>
      </ItemGroup>
    </When>
    <Otherwise>
      <ItemGroup>
        <Reference Include=”System.Data.SQLite, Version=1.0.65.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86″>
          <SpecificVersion>False</SpecificVersion>
          <HintPath>..\Lib\x86\System.Data.SQLite.DLL</HintPath>
        </Reference>
      </ItemGroup>
    </Otherwise>
  </Choose>

<Choose> <When Condition= … /> <Otherwise … /> </Choose> – it’s fun how people are trying to add “behavior” to a such static thing as XML. Well, it works, sometimes…

Detection of the current platform is based on checking of two environment variables: PROCESSOR_ARCHITECTURE and PROCESSOR_ARCHITEW6432 to detect “bitness” of running OS/processes. Details of this you can find in the post of David Wang HOWTO: Detect Process Bitness.

Working like a charm for us.

3 Comments

Follow

Get every new post delivered to your Inbox.