.

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

safd

#region CloseCommand

private RelayCommand _closeCommand;

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

        return _closeCommand;
    }
}

private bool CanClose()
{
    return true;
}

private void OnClose()
{
    Workspace.This.Close(this);
}

#endregion

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)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}

df

 

Gridview in WPF

<ListView ItemsSource="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" MaxHeight="430">
    <ListView.View>
        <GridView>
            <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}" />
        </GridView>
    </ListView.View>
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <!--<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBox_MouseLeftButtonDown" />-->
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

Terminating a WPF application

You could shutdown the app programatically as follow:

Application.Current.Shutdown();

or you could simply force a more disgraceful close:

Process.GetCurrentProcess().Kill(); 
Environment.Exit(0);

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">
    <ListView.ItemTemplate>
        <DataTemplate>
            <DockPanel LastChildFill="True">
                <TextBlock Text="{Binding FullName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            </DockPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBox_MouseLeftButtonDown" />
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

Enjoy!

Convert to binary

using functions:

[Test]
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#

http://json2csharp.com/#

http://jsonutils.com/

 

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
{
    [TestClass]
    public class MyControllerTest
    {
        private static int TestPublishNewStandsLogResultIndex;

        private static readonly List<LogEntry> TestPublishNewStandsLogResults = new List<LogEntry>
        {
            new LogEntry
            {
                Id = 32,
            },
            new LogEntry
            {
                Id = 55,
            },
            null,
            };

        private IOperationLogHandler operationLogHandler;

        [TestInitialize]
        public void Setup()
        {
              operationLogHandler = MockRepository.GenerateMock<IOperationLogHandler>();
        }

        [TestMethod]
        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.Message,
                                    ex.InnerException != null ? ex.InnerException.ToString() : string.Empty,
                                    ex.StackTrace ?? string.Empty);

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