WPF confirmation boxes

MessageBoxResult answer = MessageBox.Show("Do you want to delete this contact?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (answer == MessageBoxResult.Yes)
    Person.DeletedDate = DateTime.Now;
    new TheDataService().UpdatePerson(Person);

Working with commands in WPF


#region CloseCommand

private RelayCommand _closeCommand;

public ICommand CloseCommand
        if (_closeCommand == null)
            _closeCommand = new RelayCommand(p => OnClose(), p => CanClose());

        return _closeCommand;

private bool CanClose()
    return true;

private void OnClose()


Implementation for RelayCommand:

internal class RelayCommand : ICommand
    #region Fields

    private readonly Action<object> _execute;
    private readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    public RelayCommand(Action<object> execute)
        : this(execute, null)

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;

    #endregion // Constructors

    #region ICommand Members

    public bool CanExecute(object parameter)
        return _canExecute == null ? true : _canExecute(parameter);

    public event EventHandler CanExecuteChanged
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }

    public void Execute(object parameter)

    #endregion // ICommand Members



Gridview in WPF

<ListView ItemsSource="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" MaxHeight="430">
            <GridViewColumn Header="Date" DisplayMemberBinding="{Binding SentTimestamp, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            <GridViewColumn Header="Subject" DisplayMemberBinding="{Binding Subject, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            <GridViewColumn Header="Attachment"  DisplayMemberBinding="{Binding HasAttachments, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <Style TargetType="{x:Type ListBoxItem}">
            <!--<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBox_MouseLeftButtonDown" />-->

Terminating a WPF application

You could shutdown the app programatically as follow:


or you could simply force a more disgraceful close:


Working with ListViews in WPF

This will bind a datasource to a ListView and display it. It includes a event for mouse left button down

<ListView ItemsSource="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" MaxHeight="430">
            <DockPanel LastChildFill="True">
                <TextBlock Text="{Binding FullName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <Style TargetType="{x:Type ListBoxItem}">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBox_MouseLeftButtonDown" />


Convert to binary

using functions:

public void binaryTest()
    Func<int, long> twopow = i => 1 << i;
    Func<long, int, bool> contain2pow = (orig, pow) => (twopow(pow) & orig) > 0;
    Func<long, int> binlenght = (orig) =>  Enumerable.Range(1, int.MaxValue).Where(m=>twopow(m) >orig).First();
    Func<long, IEnumerable<bool>> bits = (orig) =>  Enumerable.Range(0, binlenght(orig)).Select(m=>contain2pow(orig,m));

    var j = 123456789;
    var b = bits(j).Reverse().Select(m=>m?"1":"0");
    var @join = string.Join("", b);
    Assert.AreEqual("111010110111100110100010101", @join);
    string conversionToBinary = Convert.ToInt32("111010110111100110100010101", 2).ToString();
    Assert.AreEqual("123456789", conversionToBinary);

json and xml to c#




Setting property by reflection

Setting property by reflection:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

Stubbing a method with multiple return values

This is how you can stub a method to return different values on each call.

TestPublishNewStandsLogResultIndex is the indexer that indicates which result is the next in line.

WhenCalled is the rhinoMocks way of accessing this predefined list.


using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FloorPlanning.Framework.Logging;
using FloorPlanning.Service.Controllers.ApiControllers.v1;
using Rhino.Mocks;

namespace Service.Tests.Handlers
    public class MyControllerTest
        private static int TestPublishNewStandsLogResultIndex;

        private static readonly List<LogEntry> TestPublishNewStandsLogResults = new List<LogEntry>
            new LogEntry
                Id = 32,
            new LogEntry
                Id = 55,

        private IOperationLogHandler operationLogHandler;

        public void Setup()
              operationLogHandler = MockRepository.GenerateMock<IOperationLogHandler>();

        public void PublishNewStandsSuccessful()
            operationLogHandler.Stub(m => m.GetLatestLogEntryForOperation(Operation.PublishStandUpdates))
                .WhenCalled(mi => mi.ReturnValue = TestPublishNewStandsLogResults[TestPublishNewStandsLogResultIndex++]);

            var controller = new PublishingController(operationLogHandler);

            var result = controller.Stands();

            //...asserts here


AppDomain Exception Handling

This is how you hook it up:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

This is an implementation of it:

/// <summary>
/// Handles the UnhandledException event of the CurrentDomain control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="UnhandledExceptionEventArgs"/> instance containing the event data.</param>
/// <exception cref="System.NotImplementedException"></exception>
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    var ex = (Exception)e.ExceptionObject;

    ServiceBase serviceBase = (ServiceBase)this.workerService;

    string message = string.Format(
                                    "Message: {0}\nInner Exception: {1}\nStack Trace:{2}",
                                    ex.InnerException != null ? ex.InnerException.ToString() : string.Empty,
                                    ex.StackTrace ?? string.Empty);

    serviceBase.EventLog.WriteEntry(message, EventLogEntryType.Error);