Standard approaches to implementing Undo/Redo

The Memento pattern is one of two standard ways of providing Undo/Redo functionality. It stores the state of the application or the part of the application that the Undo/Redo operations should apply to. The other approach is to use include an Undo() method in the Command interface while using the Command pattern. There are obvious benefits to each – one is simpler and less work to set up, and the other requires less memory.

If designing for undo/redo functionality, I would select the Memento pattern by default. I’d only look at the adapted form of the Command pattern if reasons such as memory consumption made the Memento approach unsuitable. Providing an Undo() method for every action available to the user can quickly become cumbersome, and the number and complexity of actions can expand quickly in applications. It’s best to start with the simplest approach possible and change later if additional complexity is required.

[Updated to correct spelling.]

UndoService

I recently published a generic undo/redo service on NuGet and GitHub. It is based on the momento pattern and uses delegate methods to access state.

The main benefit of this is how simple it is to use. To use it, you pass the type that is used to store state and the methods to get and set the state (most likely in wrappers to match the delegate signature). Once that is in place, you just invoke RecordState() to get the state and store it in the Undo stack, along with Undo(), Redo() and Clear() methods as appropriate.

The data structure it uses depends on whether you set a limit on the number of states that it stores. If a limit is set, it uses a dropout stack. Without a limit, it uses a standard stack.

There is no nesting or grouping of undoable actions. It is possible that I’ll add such a feature in the future but I have no specific plans to do so.

https://github.com/peterdongan/UndoService

https://www.nuget.org/packages/UndoService/

AutoScroller for UWP ScrollViewer

I recently published a couple of open source projects on NuGet and GitHub. One is UWP.AutoScroller. It auto-scrolls a UWP ScrollViewer when an element within it is dragged against its edge. It’s ported from a similar tool I wrote for Silverlight some time ago. 

I simplified its functionality. The Silverlight version also allowed you to programmatically scroll the ScrollViewer. This is not included in the new version – you just enable or disable the basic function.

I also simplified the code. In this version, handlers are added to events of the ScrollViewer itself instead of on elements within it. This is a simpler and more efficient approach.

Further information is in the project readme and the nuget documentation.

https://github.com/peterdongan/AutoScroller

https://www.nuget.org/packages/UWP.AutoScroller/

 

 

Introduction to Application-level encryption with DPAPI

Introduction

DPAPI stands for Data Protection API. It is a component in Windows operating systems which can provide symmetric encryption of any kind of data. It is the generally recommended approach for securing locally stored data, including credential information and cryptographic keys. It is used by many applications for this, including Chrome and SQL Server. A major advantage of it is that key management is taken care of by Windows.

DPAPI is accessible in .NET. It can offer convenient and inexpensive secure application-level encryption. However misusing it can result in security issues, problems decrypting data or irretrievable data. Therefore it is important to have some understanding  of how it works and to be aware of requirements for it to be used safely.

Overview

DPAPI has two forms: Machine-level and user-level. Data encrypted using machine-level DPAPI can only be decrypted on the same machine (but under any account). Data encrypted using user-level DPAPI can only be decrypted under the same account (but on any machine). User-level encryption is generally more secure and allows wider applications than machine level encryption, but can also have problems if it is misused.

User-level DPAPI works by generating a MasterKey from the user’s password. It stores this in the user’s profile, and uses this in conjunction with other secrets to create cryptographic keys. New MasterKeys are generated after periods of time, in line with an effective key management strategy.

Requirements for Safe User-level DPAPI

I’m aware of the following requirements for using user-level DPAPI safely in .NET. If it looks like I’ve left anything out then please add a comment…

  • Roaming profiles should be used so that the machine is not a point of failure.
  • The LoadUserProfile flag in the application pool needs to be set to true to allow user level encryption.
  • Mandatory profiles can’t be used for user level encryption because they are read-only.
  • The profile should only be used on one machine at a time. Concurrent logins on different machines can result in problems decrypting data. (Therefore DPAPI is unsuitable for data that needs to be encrypted/decrypted on more than one machine at a time.)
  • Profiles need to be backed up. If the profile is deleted or corrupted and cannot be recovered then the encrypted data may be irretrievably lost.
    • Keys are backed up by the domain controller. If the profile is unable to use a MasterKey it needs then it can securely retrieve the MasterKey from the domain controller. (That means that keys generated since the last backup will not be lost in the event of a restored profile. It only seems to be important that the profile is not lost entirely.)
  • In workgroup or standalone PCs administrator should not reset the profile password as this will lead to the encrypted data not being recoverable. Password reset disks can be used to safely reset the password. Obviously these themselves need to be secured. In domain PCs the keys are automatically updated as per the process described in the previous point.

I plan to add a follow-up post where I’ll describe how user-level DPAPI can be used to encrypt secrets needed by source code as part of the deployment process.

Source Material and Further Reading

https://support.microsoft.com/en-us/help/309408/how-to-troubleshoot-the-data-protection-api-dpapi

https://msdn.microsoft.com/en-us/library/ms995355.aspx#windataprotection-dpapi_topic02a

https://cheatsheetseries.owasp.org/cheatsheets/DotNet_Security_Cheat_Sheet.html

 

Serialization for Silverlight Web services: SilverlightSerializer and protobuf-net with QuickLZSharp compression

Introduction
SilverlightSerializer 2.0 and protobuf-net offer substantial improvements on the default binary serialization done by WCF. They can be used to create byte arrays for the objects being serialized in a service consumed by Silverlight. Protobuf-net is a .NET implementation of protocol buffers. protocol buffers is name of the binary serialization format used by Google, and is known to be very fast and efficient. Protobuf-net is compatible with most of the .NET family of frameworks. SilverlightSerializer is a less well-known binary serializer which was developed specifically for Silverlight. It is particularly simple to use.

I adapted a project using SilverlightSerializer to use protobuf-net. Protobuf-net offered improved reduction in the size of WCF messages, but I observed that there seemed to be a smaller difference in the message sizes with larger objects than with small ones. I decided to test how the two compared in serializing (relatively) large objects.

I also investigated the benefits of using QuickLZSharp compression on Protobuf-net serialized byte arrays. Compressing SilverlightSerializer byte arrays with QuickLZ has already been shown to be highly beneficial. For protobuf-net serialized arrays, it offered a small benefit in most cases, and a very great benefit where the serialized data consisted of duplicate strings.

Tests
The default WCF binding (basicHttpBinding) was used for all tests, which means the envelope was not encoded into binary. If binaryMessageEncoding was used then all results would be smaller (and the relative difference between the two slightly greater). Duplicate method names were used for all tests so that the envelope size would be the same in all cases.

For protobuf-net results, brackets indicate the byte array was compressed with QuickLZSharp. All SilverlightSerializer results have the compression applied. A List object was used to hold the data in all cases.

10,000 doubles (1-10000):
SS: 43,928
PB: 32,152 bytes (31,250 bytes)

10,000 strings (“1” – “10000”):
SS: 41,228 bytes
PB: (30,668 bytes)

10,000 strings (all “Hello world”):
SS: 2,760 bytes
PB: 2,137 bytes (594 bytes)

1000,000 strings (“1” – “100000”):
SS: 404,580 bytes
PB: 320,459 bytes (294,408 bytes)

Conclusions
For all tests, protobuf-net consistently resulted in messages at most 73% the size of equivalent compressed SilverlightSerializer messages. I’ve observed that there seems to be a greater reduction with objects smaller than those in the tests described above (approx. 65% based on casual observation).

QuickLZSharp compression consistently improved the message size with both. When applied to protobuf-net serialized data, the level of improvement corresponded with the level of duplication within the data being sent. In a separate project I measured the time it took to apply QuickLZSharp compression to an arbitrary object that was 3,764B before compression. It took 1 ms, and the size was reduced to 3364B. I would suggest that compression is generally worth doing, given the possible improvements. If bandwidth reduction is a priority in a Silverlight Web service then it is worth using compressed protobuf-net serialized byte arrays.

Silverlight RichTextEditor

I developed a RichTextEditor control for Silverlight. It inherits from the RichTextBox. It provides properties to get and set text formatting at the carat.

Here is an example of its use. The example is adapted from an official Microsoft sample TextEditor. In the MS sample formatting can be applied to selected text. In my version formatting can be applied on the fly, and the current formatting at the carat (or selection) is shown in the controls. This is more in-line with typical text editors. [The live sample link for the official sample is dead, but the download link works.]

[silverlight: silverlighttexteditor.xap, 950, 600]

Setting the text formatting at the carat was easy. The same code as the official sample worked after removing the condition to check the selection was not of zero length. To get the current formatting I used a SelectionChanged event handler on the control. It finds the attributes of the parent run of Selection.Start:

My initial approach was to use rtb.Selection.GetProperty(dependencyProperty) but this was problematic. It did not always return the expected result when the selection was empty. Accessing dependency properties is also generally slower.

The offical sample allows you to insert UIElements including images. This is for demonstration purposes only, and documents containing such elements cannot be saved. The example I’ve provided leaves these out.

Silverlight RichTextEditor project on Codeplex.

AutoScroller for Silverlight ScrollViewer

This is a small project I released as open source some time ago. It facilitates programmatic scrolling of a ScrollViewer in Silverlight.

ScrollViewer is a sealed class. Applying the functionality to it via a separate class seems like a neat approach.

Below is an example of its application. The functionality is applied by default in the example. Clicking the off button shows the default behaviour of the ScrollViewer. For convenience, this example is included in the source code download.

[silverlight: autoscrollviewer.xap]

The first three buttons on the right set the mode property of the AutoScroller. The ‘New Rectangle’ button adds a shape that may be dragged around the canvas, to demonstrate the autoscrolling functionality.
Automatic scrolling can be set directly also via the ScrollLeft, ScrollUp, SrollRight, ScrollDown properties. Lastly, there are properties to set the scrolling speed and the size of the canvas area that triggers the scrolling in Mode.Drag and Mode.Auto.

Download:

AutoScroller DLL
AutoScroller Source Code

A way to specify UI elements as properties declaratively in XAML

Here is an screenshot of an icon button type UserControl I developed in Silverlight:

This shows nine instances of the same UserControl, which is composed of a TextBlock and a panel containing an icon. The content of both of these are specified via properties. The challenge was to enable the panel to be specified declaratively in XAML. The problem was that you can’t use UI elements as static resources in Silverlight. For example, the following approach results in a runtime error:

<local:IconButton IconPanel="{StaticReource RectangleIcon}" Command="AddRectangle" Caption="Rectangle"/>

However, using a TypeConverter, I devised a way to allow the control to be specified like this:

<local:IconButton IconPanel="RectangleIcon" Command="AddRectangle" Caption="Rectangle"/>

A good general introduction to using Typeconverters with XAML is in Umair Saeed’s blog. The implementation of the TypeConverter class here is adapted from the generic example on that page.

//The TypeConverter class is in the System.ComponentModel namespace. The CultureInfo class is in System.Globalization.

public class IconConverter : TypeConverter
{
   public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
   {
      if (sourceType == typeof(string))
      {
         return true;
      }
      return base.CanConvertFrom(context, sourceType);
   }

   public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
   {
      string strValue;
      if (value is string)
      {
         strValue = (string)value;
         if (strValue == "RectangleIcon")
            return Icons.Rectangle; 
         else
            return new Grid();
      }
      return base.ConvertFrom(context, culture, value);
   }

The Icons class just gives a convenient way of referring to the Icons. The code below can return a UserControl, or the root element from it. Note that in the latter case that you need to remove the root element from the created UserControl Instance, or an error will be generated: A UI element cannot be contained in multiple UI elements.

The RectangleIcon class it refers to is a UserControl just containing the Grid with the rectangle.

Lastly, here is how the implementation of the IconPanel property in the IconButton class:

private Panel _iconPanel;

[TypeConverter(typeof(IconConverter))]
public Panel IconPanel
{
   get
   {
      return _iconPanel;
   }
   set
   {
       _iconPanel = value;
       IconHolder.Content = _iconPanel;
    }
}

IconHolder is an empty UserControl which will hold the icon. Adding it directly as a child to the root element is also possible – however you need to make sure the names of the panels are different. Otherwise you may try to add a grid named LayoutRoot to another grid named LayoutRoot – which results in the error “Value does not fall within expected range” being thrown at runtime.

 

[Edited 21 July 2019 – restored image and code excerpts]

‘Hand’ Cursor and Website Icons

When you hover over a UI element and the cursor changes, this is an implementation of the Cursor Invitation design pattern. It indicates to the user that the UI element may be interacted with. The convention is to use it only when the interaction may be non-obvious, so it’s not used with standard buttons.

I was wondering if the convention was to use it with buttons in the form of icons. I couldn’t find anything about it online, so I looked at some Websites using icon-buttons to see what the consensus was. In all examples I found, hand cursors were used for icon buttons. This is logical, since not every icon on every Webpage is interactive. This isn’t consistent with Windows, where the cursor doesn’t change over icons. (This is also logical – every icon in Windows is interactive by default, so the extra prompt is unnecessary.)

Icon button at bing.com
Icon button at bing.com

It’s very easy to implement this in Silverlight – in both XAML and code-behind. You can just set the cursor property to the hand cursor.Eg:

XAML:
<Grid x:Name="LayoutRoot" Cursor="Hand">

C#:
target.Cursor = Cursors.Hand;

Even better, setting IsEnabled to false stops the cursor change from occurring  – so there’s no need to change the cursor property manually when the button is disabled.