Only the code tells the truth

Treat your code like any other composition, such as a poem, an essay, a public
blog, or an important email. Craft what you express carefully, so that it
does what it should and communicates as directly as possible what it is doing;
so that it still communicates your intention when you are no longer around.
Remember that useful code is used much longer than ever intended. Maintenance
programmers will thank you. And, if you are a maintenance programmer
and the code you are working on does not tell the truth easily, apply the
aforementioned guidelines in a proactive manner. Establish some sanity in the
code, and keep your own sanity.

– Peter Sommerlad (from “97 things every programmer should know”)

Prism UWP for beginners: lifecycle

 

In this post we’ll explore the management of the lifecycle of a UWP app inside the OS.

Classic programs (Win32, for example) have two states: not running and running. When the typical desktop app is running it use all the RAM and CPU it needs, even when it is in the background. This is a problem in the world of universal apps because many types of device have very limited battery, CPU, and memory. So in this ecosystem we need to be green and free resources as soon as possible.

Windows comes to our help about power management but we need to know a few more things that we have to manage in our code. The OS can suspend our app when it wants in some cases and we need to give our useres the best user experience.

By default, apps that are not in the foreground are suspended which results in power savings and more resources available for the app currently in the foreground.

updated-lifecycle

In MSDN documentation we can find a detailed explanation of every status and the suggested action to take:

image

When a user leaves our application by switching to another one without terminating, he or she expects to find all the things in place when he/she’ll come back. The termination by the OS has to be transparent. So we need to save the state of the app and restore when the OS will restore the app.

Let’s do it!

Plain data

When we need to save simple data like boolean, strings, or numeric values we decorate with the RestorableState attribute in our viewmodel the properties that we need to save and restore. For example we have a TextBox binded to a string property:

  <StackPanel>
        <TextBlock Text="Simple property restore" />
        <TextBox Text="{Binding SimpleProperty, Mode=TwoWay}" />
  </StackPanel>

And this is our code behind:


class RestoreStatePageViewModel : ViewModelBase
{
[RestorableState]
public string SimpleProperty
{
get { return _simpleProperty; }

set
{
_simpleProperty = value;

SetProperty(ref _simpleProperty, value);
}
}

public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
{
base.OnNavigatedTo(e, viewModelState);
}

private ISessionStateService _sessionStateService;

private string _simpleProperty;
}

That’s it! Now: how to try? How can we force the OS to suspend our App? Visual Studio helps providing the Debug Location toolbar with the Lifecycle Events dropdown.

image

If this toolbar is not visible we find it by right-clicking in the white space of the main toolbar and select Debug Location.

image

Now we can launch our app and write something in the TextBox. Then we select Suspend and shutdown in the Lifecycle events dropdown. Visual studio will stop debugging and the app terminated. Now we hit F5 again to restart our app and we’ll find that the TextBox has the same value we writed before.

Complex data

Sometimes we have to save and restore complex or custom data. In this scenario we rely on the SessionStateService provided by Prism.

We register this service during the bootstrap in the App.xaml.cs code in the OnInitializeAsync method:

 protected override Task OnInitializeAsync(IActivatedEventArgs args)
        {

            Container.RegisterInstance(SessionStateService);

            return base.OnInitializeAsync(args);
        }

Let’s say we have a class that represents our Twitter Timeline. We need to decorate the class and the properties we want to save and restore with the DataContract and the DataMember attributes respectively.

This is because the Prism framework needs to serialize and deserialize our class and with UWP we don’t have the [Serializable] attribute we have in the standard .net environment.

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace IC6.Buongiorno.Services.Twitter
{
    [DataContract]
    public class TwitterTimeline
    {
        [DataMember]
        public string Timeline { get; private set; }

        public TwitterTimeline(IEnumerable<string> tweets)
        {
            Timeline = string.Join("\r\n\r\n\r\n", tweets);
        }
    }
}

We also need to configure Prism to serialize our custom class. We do this the App.xaml.cs code in the override of the OnRegisterKnownTypesForSerialization() method in which we have to register, in the SessionStateService, every custom class we’re going to use in the application, like in the following sample:

 protected override void OnRegisterKnownTypesForSerialization()
        {
            base.OnRegisterKnownTypesForSerialization();

            SessionStateService.RegisterKnownType(typeof(TwitterTimeline));
        }

Our class is now ready to be saved and restored.

In our viewmodel we need to save our timeline and we write:

public void SaveState()
{
if (_sessionStateService.SessionState.ContainsKey(SettingNames.Timeline.ToString()))
                {
                    _sessionStateService.SessionState.Remove(SettingNames.Timeline.ToString());
                }
                _sessionStateService.SessionState.Add(SettingNames.Timeline.ToString(), twitter);
}

To restore the state the best place is the OnNavigatedTo event.

 public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(e, viewModelState);

                        if (_sessionStateService.SessionState.ContainsKey(SettingNames.Timeline.ToString()))
            {
                var twitter = _sessionStateService.SessionState[SettingNames.Timeline.ToString()] as TwitterTimeline;

                Timeline =  twitter.Timeline;
            }

                    }

We can test all this with the same procedure as before.

TL;DR

In this post we explored the concepts of lifecycle management and how to use Prism event to save and restore the state of our app to provide the best experience to our users.

If you want to learn more:

3+ ways to try to be a better team leader

You did it! Now you’re in charge.

You are the team leader of your deparment. Now what?

It’s hard to be a leader. It’s even harder to be a respected one.

How do you earn the trust of your teammates? How do you know if they respect you and if they will follow you? These are the questions that bothers me every single day.

I’m far from being the team leader that I would like but I try every day to be as good as I can and to improve just a little bit; to be this week a little less worse than the previous.

images.jpg

I have 4 rules that I try to follow (and sometimes I fail).

1. Don’t criticize, condemn or complain

This is the first principle of Dale Carnegie‘s How to win friends and influence people. Try to not criticize when someone do a mistake: we’ve done mistakes so many times that we’re no-one to elevate ourselves and judge other people. Instead we try to understand why that kind of mistake was done and find a way so we can learn from that and possibly do not repeat the same thing in the future.

This is the hardest rule, to me. When I’m upset about something or when my mood is not so good this principle is very hard to follow. I try to have an open-minded attitude and to be patient.

2. Give Honest, Sincere Appreciation

This is the second principle of Dale Carnegie. I know: Dale Carnegie influenced me a lot.

People need appreciation like air. We cannot live today with the air we breathed yesterday. If a member of the team has done a good job we say thank you and appreciate what has been done. The appreciation is better if specific and precise.

There is a catch, though. We must mean it; really mean it because otherwise it’ll come across as flattery.

This is my favourite rule. I’m excited to give appreciation. I like to say bravo when someone does something good or on time. Being on time is hard so it has to be recognized. I like to appreciate skills that I don’t have, too. It makes me glad to be part of diverse team with many skills.

3. Help the team

As leaders our main goal is to help. Help can spread across many activities: explaining things over and over again until they’ve been understood, doing pair programming to solve a hard problem, doing a phone call to a coworker to ask if everything is ok. We also help the team by organizing a better way to work, to avoid distractions and to be more focused.

4. Apologize early

We all do something wrong. As leaders we are the example to follow and when we do mistakes (and we do a lot) we must be humble and apologize as soon as possible and with honesty.

Conclusions

This is my set of rules that I try to apply every day. Some days are good, some days are worse.

I think that, at the end of the day, the most important thing is to work in a positive environment where feedback is encouraged and errors are recognized as occasions to improve.

What do you do every day to work better your teammates?

Prism UWP for beginners: navigation

In this post we’ll talk about the navigation with Prism in UWP. With navigation I mean the technique to go from one page to another of your app. The operation in UWP/XAML is tipically performed with the Frame class that’s available only in the code-behind of a Page because it inherits from Frame. This way we do not respect the MVVM pattern. Prism comes in our help providing a wrapper to the Frame class accessible from the ViewModel: it’s the NavigationService. This isn’t a very new name to us because we found it in the bootstrapper.

protected override Task OnInitializeAsync(IActivatedEventArgs args)
{
//...
Container.RegisterInstance(NavigationService);
//...
}

We saw it at the end of the bootstrap procedure in the OnLaunchApplicationAsync method, too.

protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
NavigationService.Navigate(PageNames.Main.ToString(), null);
return Task.FromResult(true); //This is a little trick because this method returns a Task.
}

To try the navigation system we create a SettingsPage in the View folder and then we’ll navigate to that page with a button in the MainPage.

Immagine

To go to there we need a command in the MainPageViewModel class and bind it in the MainPage view.

public class MainPageViewModel : ViewModelBase
{
public DelegateCommand GoToSettings { get; private set; }

//...
}

In the constructor we initialize the GoToSettings property.

public MainPageViewModel(ITwitterService twitterService, IWeatherService weatherService, INavigationService navigationService)
{

_navigationService = navigationService;

GoToSettings = new DelegateCommand(() =&amp;gt;
{
_navigationService.Navigate("Settings", null);
});
}

In the constructor we added a parameter: the INavigationService reference. This new dependency will be handled by Unity container when resolving an instance of MainPageViewModel. The GoToSettingsCommand is composed by a single line of code where we call the Navigate method with the first argument that is the name of the page where we want to go and the second argument is to add additional information: since we have no additional data we write null.

In this example the Settings page allows us to change the backgorund image of the main page. We notice that in the upper left corner of the application a back. This is handeld by the UWP framwork when detects a navigation.

This back button can be different based on the device where the app is running: phone, tablet or pc. For example in a tablet with tablet mode enabled it will appear on the navigation bar at the botton of the device. In the MSDN we can find al the details.

Screenshot_2.png

When we click the back button we go back to the main page.

When navigating in our view-model we can use two methods to detect when we land into a page or when we leave a page. OnNavigatedTo is callaed when navigation in performed to a page. OnNavigatingFrom is called when navigating away from the page.

   public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(e, viewModelState);

//Loading state custom logic.
        }

        public override void OnNavigatingFrom(NavigatingFromEventArgs e, Dictionary<string, object> viewModelState, bool suspending)
        {
            base.OnNavigatingFrom(e, viewModelState, suspending);
//Save state logic.
        }

TL;DR

In this post we explored the basic concept about navigating with Prism in UWP App with the Navigation Service and the events that Prism offers to detect the transition from one page to another.

If you want to learn more you can refer to the Prism official website and MSDN. Happy coding!

Prism UWP for beginners: binding and commands

We setup the foundation of a Prism UWP app in the last post. Now we explore binding and commands.

Binding

Binding is the mechanism that connects the UI to the view-model properties to display data in the page and to receive input from the user (with two way binding). We can do binding by implementing the INotifyPropertyChanged interface in our view-model so the view is notified when a property in the view-model changes.

Prism helps us by providing classes that we can use to avoid reinventing the wheel and to start quickly with binding: VisualStateAwarePage and ViewModel.

We use VisualStateAwarePage instead of Page when we create a new view, for example:

<mvvm:SessionStateAwarePage 
x:Class="IC6.Buongiorno.Views.MainPage"
mvvm:ViewModelLocator.AutoWireViewModel="True"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:IC6.Buongiorno.Views"
xmlns:mvvm="using:Prism.Windows.Mvvm" >
    <mvvm:SessionStateAwarePage.Background>
        <ImageBrush Stretch="Fill" 
            ImageSource="ms-appx:///Assets/wallpaper.jpg" />
    </mvvm:SessionStateAwarePage.Background>

    <Grid Margin="50">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="10*" />
        </Grid.ColumnDefinitions>

        <StackPanel Grid.Column="0"  Margin="10">
            <Button Command="{Binding Update}" Foreground="White">Update
            </Button>
            <TextBlock Text="{Binding Timeline}" Foreground="White" TextWrapping="Wrap" />
        </StackPanel>
        <StackPanel Grid.Column="1"                     HorizontalAlignment="Right">
            <TextBlock Text="{Binding WeatherDescription}" FontSize="32" Foreground="White" />
            <TextBlock Text="{Binding WeatherTemperature}" FontSize="50" Foreground="White" />
        </StackPanel>
    </Grid>
</mvvm:SessionStateAwarePage>

We must replace the Page type in the code-behind, too.

using Prism.Windows.Mvvm;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace IC6.Buongiorno.Views
{
    ///
<summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>

    public sealed partial class MainPage : SessionStateAwarePage
    {
        public MainPage()
        {
            InitializeComponent();

        }

    }
}

We create a MainPageViewModel class in the ViewModels directory and inherit from ViewModel. ViewModel is class of Prism that provides several helpers. In this example we create 3 properties in the ViewModel: Timeline, WeatherDescription, WeatherTemperature. Timeline will expose our Twitter timeline to the UI, WeatherDescrption will expose a brief textual description of the current weather (like “sunny”, “heavy rain”) and WeatherTemperature will expose the current temperature. This is the full MainPageViewModel.

using IC6.Buongiorno.Services.Twitter;
using IC6.Buongiorno.Services.Weather;
using Prism.Commands;
using Prism.Windows.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IC6.Buongiorno.ViewModels
{
    public class MainPageViewModel : ViewModelBase
    {
        ///<summary>
        /// Gets the command to Update Timeline and weather data.
        /// </summary>

        public DelegateCommand Update { get; private set; }

        ///<summary>
        /// Gets or sets the Twitter timeline.
        /// </summary>

        public string Timeline
        {
            get { return _timeline; }
            set { SetProperty(ref _timeline, value); }
        }

        ///<summary>
        /// Gets or sets the current weather description.
        /// </summary>

        public string WeatherDescription
        {
            get { return _weatherDescription; }
            set { SetProperty(ref _weatherDescription, value); }
        }

        ///<summary>
        /// Gets or sets the current weather temperature.s
        /// </summary>

        public string WeatherTemperature
        {
            get { return _weatherTemperature; }
            set { SetProperty(ref _weatherTemperature, value); }
        }

        ///<summary>
        /// Constructor with services.
        /// </summary>

        /// <param name="twitterService">The <see cref="ITwitterService"/> to access Twitter data.</param>
        /// <param name="weatherService">The <see cref="IWeatherService"/> to get current weather information.</param>
        public MainPageViewModel(ITwitterService twitterService, IWeatherService weatherService)
        {
            if (twitterService is null)
            {
                throw new ArgumentNullException(nameof(twitterService));
            }

            if (weatherService is null)
            {
                throw new ArgumentNullException(nameof(weatherService));
            }

            _twitterService = twitterService;

            _weatherService = weatherService;

            Update = new DelegateCommand(async () =>
            {
                Timeline = (await _twitterService.GetTimelineAsync()).Timeline;

                var weatherInfo = (await _weatherService.GetWeather());

                WeatherDescription = weatherInfo.Description;

                WeatherTemperature = $"{weatherInfo.Temperature} °C";
            });
        }

        private string _weatherTemperature;

        private string _weatherDescription;

        private readonly ITwitterService _twitterService;

        private readonly IWeatherService _weatherService;

        private string _timeline;
    }
}

In the code above the SetProperty method is provided by the ViewModel base class and with this we leverage the INotifyPropertyChanged interface to inform the UI that a property has updated its value.

In the constructor we have two dependencies: ITwitterService and IWeatherService. They are handled by the Unity container that we configured in the previuos post. When we’ll ask Unity to resolve an instance of MainPage it will automatically resolve ITwitterService and IWeatherService avoing to us all the heavylifting. This way our code remain clean and easier to read and mantain.

The view-model is automatically linked to the view by Prism beacuse in the page we declared mvvm:ViewModelLocator.AutoWireViewModel="True".

Commands

Commands are the mechanism to support the user interaction without using event handlers. In the Prism framework we find the DelegateCommand that implements the ICommand interface required by XAML.

The ICommand interface exposes a method called CanExecute that is very powerful. With a boolean condition we check if the command is enabled or not. In the MainPageViewModel class we declare an ICommand property and in the constructor we assign a DelegateCommand. In this example we’re getting the timeline from the Twitter service and the weather data from the weather service and assingn to the properties.

In the XAML code above we bind the button Update to this command with the standard binding syntax in the Command property of the Button.

TL;DR

In this post we explored the concepts of bindings and the commands to handle user input and display data retrieved with our services.

Cattura.PNG

Stay tuned for other Prims UWP posts.

Prism UWP for beginners: setup

I want to learn Prism because it may be helpful in some future projects. To better understand how it works I need a target. I’d like to create a simple UWP app that displays my Twitter timeline and the local weather based on the GPS. Prism will help me to adopt the MVVM architeture and IoC/DI concepts. The MVVM and IoC/DI topics are out of the scope of this post.

Setup

I started a new UWP project with Visual Studio 2017 and then imported the Prism.Windows and Prims.Unity NuGet packages. Prism.Windows is the “core” library for the UWP techology and Prism.Unity is the IoC/DI container.

Screenshot_1.png

Conversion to Prism

I converted the Universal app to a Prism Universal app by configuring the bootstrapper. The bootstrapper is a required procedure by the Prism framework to properly initialize all the infrastructure. In vanilla UWP, the bootstrapper is the App class. I edited the App class so that it doesn’t inherit from the native Application class but from a Prism class called PrismUnityApplication.

This is the full App.xaml file.

<prismUnity:PrismUnityApplication x:Class="IC6.Buongiorno.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prismUnity="using:Prism.Unity.Windows"
RequestedTheme="Light">

</prismUnity:PrismUnityApplication>

 

This is the full App.xaml.cs file.

using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using Prism.Unity.Windows;
using Prism.Windows.AppModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Resources;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using IC6.Buongiorno.Services.Twitter;
using IC6.Buongiorno.Services.Weather;

namespace IC6.Buongiorno
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : PrismUnityApplication
{


public App()
{
InitializeComponent();
}


protected override UIElement CreateShell(Frame rootFrame)
{
var shell = Container.Resolve<Shell>();
shell.SetContentFrame(rootFrame);
return shell;
}

/// <summary>
/// Logic of app initialization.
/// This is the best place to register the services in Unity container.
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
protected override Task OnInitializeAsync(IActivatedEventArgs args)
{
System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>> OnInitializeAsync called.");

Container.RegisterInstance<ITwitterService>(new TwitterService());

Container.RegisterInstance<IWeatherService>(new WeatherService());

Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader()));

Container.RegisterInstance(SessionStateService);

Container.RegisterInstance(NavigationService);

return base.OnInitializeAsync(args);
}



protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
{
NavigationService.Navigate(PageNames.Main.ToString(), null);

return Task.FromResult(true); //This is a little trick because this method returns a Task.
}
}
}

 

I created a Paged called Shell. The Prism definition of shell is:

The main window of an application where the primary UI content is contained.

Shell is called in the CreateShell method triggered by the Unity framework to create the main window of the application.

The OnInitializeAsync method is the place to initialize the Unity container. Here I registered my services. With registering I mean telling Unity that, for example, every time I need an ITwitterService it has to give me an instance of TwitterService. I also register the NavigationService and SessionStateService that I’ll explain in other posts.

I created the standard MVVM folders because Prism is convention based for some of its features.

image

I deleted the default MainPage.xaml file and created a new one in the Views directory as shown in the image above.

Inside OnLaunchApplicationAsync I called the NavigationService.Navigate method to navigate to the MainPage which accepts as first parameter the name of the page (the name of the View without the Page suffix): by passing as parameter the value “Main” Prism searches, in the Views folder, a page called MainPage.xaml. The second parameter is null because I didn’t have additional parameters to pass. The last statement is a little trick because this method returns a Task and I created a fake one with a constant true value.

TL;DR

I made my first steps with Prism in a UWP application: I created the shell and setup the bootstrapper.

In the next post I’ll explore other basic concepts like binding and commands.

The best tip on software estimation I’ve ever found

Count if at all possible. Compute when you can’t count. Use judgment alone only as  last resort. (Steve McConnell)

imagesKKBBN896.jpg

Count-first is the approach that Steve McConnell suggests in his Software Estimation book.

If you can count the answer directly you should that. […]
If you can’t count the answer directly, you should count something else and then compute the answer by using some sort of calibration data.

Reading about this approach makes me think about how I estimated things in the past. My job is changing and the tasks of estimating and scheduling are more frequent. I know that software estimation is hard and crucial for every project to succeed.

If you, like me, are having troubles on software estimation I strongly recommend Steve McConnell’s books “Software Project Survival Guide” and “Software Estimation”. They are like strong related cousins; you’ll be a better software project manager if you know how to estimate and you’ll estimate better if you know how a software project has to be done.