• Kirill Osenkov

    Random Gradient Wallpaper Generator

    • 10 Comments

    Oops, I did it again :) Created a new CodePlex project, that is.

    Introducing http://wallpaper.codeplex.com – a simple tool to generate a nice random wallpaper and display it on your desktop with just one click:

    WallpaperGenerator1.png

    WallpaperGenerator3

    • Randomize - assigns random colors to all four corners
    • Set as Wallpaper - saves the picture to My Pictures\GradientWallpaper.bmp and sets the Windows Desktop wallpaper to this file. It will overwrite the file if it exists.
    • Save colors to text file - appends the RGB values of the current colors to the "colors.txt" log file in the program's directory (in case you liked the colors and want to save the colors, not the image)
    You can also click on each of the four corners and pick any color yourself. There are a total of 79228162514264337593543950336 possible wallpapers that can be generated this way.

    WallpaperGenerator4WallpaperGenerator5WallpaperGenerator6WallpaperGenerator7WallpaperGenerator8WallpaperGenerator9WallpaperGenerator10WallpaperGenerator11

    I wrote this in an evening a couple of years ago and it was just lying around, so I decided to publish it so that it doesn’t get lost. Of course, one could take WPF, MEF, Bling, pixel shaders and build it out into a super-extensible plug-in-based photoshop-like fractal-ray-tracing rendering wallpaper generator, but... For now, let’s stick with a simple WinForms app. But hey, it’s open source, feel free to contribute if you like ;)

  • Kirill Osenkov

    Dump Environment Folder Paths

    • 7 Comments

    This is just a quick snippet to dump the value of Environment.GetFolderPath for all special folders on a machine (so I don’t have to write it again next time):

    public static string DumpEnvironmentPaths()
    {
        var paths = Enum.GetValues(typeof(Environment.SpecialFolder))
            .Cast<Environment.SpecialFolder>()
            .Select(folder => folder + " = " + Environment.GetFolderPath(folder))
            .Aggregate((line1, line2) => line1 + Environment.NewLine + line2);
        return paths;
    }

    Also, I’m using the opportunity to give Rick Strahl’s CodePaste.NET service a spin: http://codepaste.net/uo7zx8.

    “CodePaste.NET is a public site for pasting snippets of code and linking to them from social network sites.”

    As for the code itself (envisioning potential rotten tomatoes flying my way), several things are probably worth mentioning:

    1. First, the code is written in a more functional style, being more explicit about its intent. I think it shows more clearly the input data and the output data, how the data flows and what operations are performed on the input data.
    2. Second, I have a temporary local variable instead of returning the expression immediately. This is for easier debugging, because if you don’t have a temporary variable, you won’t be able to view the return value of the method easily in the debugger. With a temporary local, you can put a breakpoint on the return statement and inspect the results of the query. Someday the tools will be improved and will allow to inspect the return value of methods.
    3. I’m using Aggregate instead of string.Join or StringBuilder because it composes better. On large data volumes, this approach is horrible because it will allocate a ridiculous amount of unnecessary intermediate strings. StringBuilder and string.Join are much more frugal in this respect, so don’t use Aggregate with strings this way. However, in this particular example, the number of strings is O(1), so I just picked the approach that composes better. Unfortunately, string.Join doesn’t compose well at all and was never intended to be used in a fluent API.
  • Kirill Osenkov

    Tip: Don’t enter your CodePlex credentials every time

    • 0 Comments

    I just ran across an awesome tip at Scott’s blog that is going to save me a whole lot of time: Save Your Codeplex Repository Credentials

    I was entering my username and password everytime I connected to a CodePlex TFS server. Now I don’t have to!

    P.S. To make this work on XP, go to Control Panel –> User Accounts –> click your account –> in the leftmost pane click Manage My Network Passwords:

    image

    image

  • Kirill Osenkov

    ColorPicker Control for WPF/Silverlight

    • 8 Comments

    A while back I was looking around for a color picker control for Live Geometry. The ColorPicker from http://silverlightcontrib.codeplex.com was exactly what I was looking for:

    Get Microsoft Silverlight

    (live preview needs Silverlight 3.0)

    Using the control in your code

    I just took the source from CodePlex and embedded it in my project. You need 5 files:

    image

    Alternatively, you can reference the binary which you can download from the SilverlightContrib CodePlex project site. Pay attention that generic.xaml contains the template for the control, so don’t forget the xaml. The control will work just fine with WPF and Silverlight, which is really a great thing, especially if you’re multitargeting.

    To include the control in your application, here’s the basic code:

    <sc:ColorPicker SelectedColor="LightGreen" />

    Don’t forget to add an XML namespace:

    xmlns:sc="clr-namespace:SilverlightContrib.Controls"

    How does the gradient work?

    The source code for this control is very good for educational purposes. For instance, I had no idea how they create the big gradient for every possible hue. Well, it’s genius and it’s simple. In generic.xaml:

    <Canvas Canvas.Top="0" Canvas.Left="20">
        <Rectangle x:Name="ColorSample" Width="180" Height="180" Fill="Red"></Rectangle>
        <Rectangle x:Name="WhiteGradient" IsHitTestVisible="False" Width="180" Height="180">
            <Rectangle.Fill>
                <LinearGradientBrush StartPoint="0,0" EndPoint="1,0">
                    <GradientStop Offset="0" Color="#ffffffff"/>
                    <GradientStop Offset="1" Color="#00ffffff"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle x:Name="BlackGradient" IsHitTestVisible="False" Width="180" Height="180">
            <Rectangle.Fill>
                <LinearGradientBrush StartPoint="0,1" EndPoint="0, 0">
                    <GradientStop Offset="0" Color="#ff000000"/>
                    <GradientStop Offset="1" Color="#00000000"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Canvas x:Name="SampleSelector" IsHitTestVisible="False" Width="10" Height="10" Canvas.Left="100" Canvas.Top="96">
            <Ellipse Width="10" Height="10" StrokeThickness="3" Stroke="#FFFFFFFF"/>
            <Ellipse Width="10" Height="10" StrokeThickness="1" Stroke="#FF000000"/>
        </Canvas>
    </Canvas>

    This canvas contains layers like in a cake. ZIndex of objects is stacked bottom to top, so the solid rectangle with initially red background is on the bottom.

    Above it, there is a horizontal white gradient fill, completely white on the left and completely transparent on the right.

    Above it, there is a vertical black gradient fill, completely black on the bottom and completely transparent on the top.

    As these gradients overlay, the transparency over the initial solid background creates the desired effect – the actual color is in top-right, where both gradients are 100% transparent. The white spot is in top-left, where the white gradient is most intense and black gradient fades out. Same for the black edge of the gradient.

    Also, it is well worth studying how the template is written – I learned a lot from this sample.

    My fixes

    Since I conveniently borrowed the source code for my project, I did several fixes for my own purposes. Ideally I should contribute the fixes back to SilverlightContrib, but I can never get around to it.

    First of all, I reordered the two StackPanels in the template so that the actual selected color is on top. I also made it collapsible and collapsed by default. You can expand the control by clicking it like a combobox. Unlike a combobox, you have to explicitly click the color area to collapse it again.

    Get Microsoft Silverlight

    I’ve enabled this by adding an Expanded property:

    public bool Expanded
    {
        get
        {
            return m_chooserArea.Visibility == Visibility.Visible;
        }
        set
        {
            var visibility = value ? Visibility.Visible : Visibility.Collapsed;
            if (m_chooserArea.Visibility == visibility)
            {
                return;
            }
            m_chooserArea.Visibility = visibility;
        }
    }

    When clicking on the color area, I just call Enabled = !Enabled to toggle it and it does the magic for me. The default value for this is obviously the default visibility of m_chooserArea, which is specified in XAML template (Visibility=”Visible” to set to true by default).

    Other fixes are not as interesting. I fixed a division by zero in ColorSpace.ConvertRgbToHsv (they had h = 60 * (g - b) / (max - min); and didn’t check if min == max). There are a couple of other things which I don’t remember off the top of my head. I’d have to view TFS history to remember what those were. If you’re willing to help and incorporate these fixes to the original project, I’ll dig this up, just let me know :)

    Conclusion

    Both Sara Ford and myself agree that this control deserves both thumbs up:

    image

  • Kirill Osenkov

    Reflection with dynamic

    • 0 Comments

    This past summer the Visual C# IDE team was fortunate enough to have Paul van Brenk intern with us. Paul is a great guy and an experienced .NET developer from Rotterdam, Netherlands, who is interested in Azure, cloud computing and many other things. He also happens to be one of the contributors for dasBlog, which I think is seriously cool.

    Paul and I were sharing an office during his internship and I was the “coach”, i.e. the guy who gets to answer all intern’s questions and helps figure things out :)

    Anyway, once we were talking about how to simplify the mess of calling private members using reflection and dynamic came into conversation. So Paul went ahead and wrote some C# 4.0 code that greatly simplifies calling private members using dynamic. Check out his blog: http://www.paulvanbrenk.com/blog/2009/05/30/UsingDynamicForEvil.aspx

    There are several things I’d like to shed more light on.

    Dynamic usage scenarios

    It’s a common misconception that dynamic can only be used for narrow interop scenarios. People came up with ways to use dynamic in a lot more scenarios.

    A common theme emerges from such usages: delay the name resolution (binding) to runtime. Instead of hardcoding the symbols known to compiler, we just specify source strings that have to be used at a later stage at runtime for lookup.

    Dynamic gives you nicer syntax to express member calls – you express them in your code using usual C# syntax (but without type checking), and the compiler does the heavy lifting of “quoting” the code down to the runtime. If you inspect the generated code, you will see that the compiler is taking your neat member call syntax and generating a complex call site data structure that contains metainformation about the call.

    How the language design team designed the dynamic feature

    From previous versions of C# you will notice that the language design team is clever when adding new features. They don’t just hardcode a feature into the language, they define an interface and implement the feature against that interface. Not literally, mind you. On the contrary, they rather use duck-typing in most cases, but still there is a contract defined somewhere and the feature works against that contract. Let me give a couple of examples:

    • foreach – they could have added foreach just to arrays. Instead, they “designed against an interface” and said: foreach will work against any IEnumerable implementation. Moreover, the contract of the feature is actually broader and is specified using duck-typing and not an explicit interface. foreach actually works against anything that has a GetEnumerator method, it does not have to implement IEnumerable. The extensibility here is that you can plug-in your own enumerator whatever it is and foreach will work just fine with it.
    • LINQ – again, the language design team said: query syntax will just translate into a well-defined set of methods (Select, Where, etc.). The extensibility here is that you can define your own Select, Where, etc. and LINQ will rewrite the query expressions against your own methods – the queries will continue to just work with your own implementation of the query pattern.
    • dynamic – and here, in C# 4.0, they didn’t just add dynamic. They defined an abstraction layer (an interface) that allows you to plug in your own implementation and the feature (dynamic) will work fine with it.

    In other words, they encapsulated an object with runtime callable members into an interface (IDynamicMetaObjectProvider) and provided default base implementation (DynamicObject). What this gives you is the ability to plug in your own implementation and dynamic will work against it.

    Effectively, this means that you can intercept member calls on any object, if these calls are dynamic. The secret of “abusing” dynamic is to use member call syntax for stuff other than calling a method. By redefining DynamicObject members you handle member calls in any way you want (usually some sort of lookup by string) – dictionary lookup, XML element and attribute lookup, reflection MemberInfo lookup, and so on.

    Now whether this all is good or bad is a totally separate discussion.

  • Kirill Osenkov

    First videos of the structured editor prototype

    • 15 Comments

    Disclaimer: the structured editor work described in my posts is unrelated to my work at Microsoft. Everything shown is my personal research done as part of my MSc thesis during 2004-2007. Also, it’s not ready for real use and does not cover all the features of even C# 1.0. It’s a concept prototype and work in progress.

    Introduction

    As part of my research back in school I was building an experimental structured editor for C#. Now I’ve decided to publish the sources and binaries on CodePlex:

    http://structurededitor.codeplex.com

    A detailed discussion of structured editors deserves a separate post, which is coming soon. For now, to give a better idea of how the editor works, I’ve recorded six short videos showing the different features below. If your blog reader doesn’t support iframes, I recommend you view this post in the browser.

    What is a structured editor?

    Programs are represented as text by most code editors. Structured editors, on the contrary, directly display the syntax tree of a program on screen and allow the user to manipulate the tree directly (think MVC: program parse tree is a model, the editor displays a view of it):

    This way the visual layout better illustrates the structure of the program and allows for atomic operations on the language constructs. A structured editor lets developers avoid syntax errors and concentrate on the meaning of the program instead of formatting.

    1. Introduction

    2. Editing

    You will notice that there is no intellisense and coloring at the expression level – I did build a SharpDevelop add-in that hosts the structured editor control inside the SharpDevelop project system (DOM), but these videos were recorded on a stand-alone version of the structured editor control hosted inside an empty windows form. Also the support at the expression level is rudimentary, because so far I’ve concentrated the most at declaration level (namespaces, types, members) and statement level (except for single-line statements such as assignments).

     

    3. Drag & Drop Support

    4. No Parser Means Less Syntax

    5. Properties

    6. Modifiers

    Background

    Structured editing is a topic surrounded with scepticism and controversy for the past 20-30 years. Some argue that directly editing the AST on screen is inflexible and inconvenient, because the constraints of always having a correct program restrict the programmer way too much. Others expect structured editors to be more helpful than text editors because the user operates atomically and precisely on the language constructs, concentrating on the semantics and not on syntax.

    In summer 2004, my professor Peter Bachmann initiated a student research project - we started building a structured editor for C#. I took part because I was deeply persuaded that good structured editors can actually be built, and it was challenging to go and find out for myself. After the original project was over, I took over the basic prototype and evolved it further to the state it is today.

    As one of numerous confirmations for my thoughts, in 2004, Wesner Moise wrote:

    ...I see a revolution brewing within the next three years in the way source code is written.

    Text editors are going to go away (for source code, that is)! Don't get me wrong, source code will still be in text files. However, future code editors will parse the code directly from the text file and will be display in a concise, graphical and nicely presented view with each element in the view representing a parse tree node. ...

    I remember how I agreed with this! After three years, in 2007, the prototype implementation was ready - it became the result of my master's thesis. I still agree with what Wesner was envisioning in 2004 - with one exception. Now I believe that structured editors shouldn't (and can't) be a revolution - fully replacing text editors is a bad thing to do. Instead, structured editors should complement text editors to provide yet another view on the same source tree (internal representation, or AST).

    My conclusions about structured editors

    1. Text-based editors aren’t going away anytime soon.
    2. Structured editors can only succeed by evolution, not revolution – hybrid approach and ability to toggle between text and structure is the way to go.
    3. The main difficulty with structured editors is getting the usability right.
    4. The right approach is solving all the numerous little problems one by one – find a solution for every situation where a text editor is better (from my experience, for any advantage of a text editor, a good structured solution can be found).
    5. You need a graphical framework with auto-layout such as WPF to build a structured editor.
    6. Don’t try to build a universal editor editor that can edit itself – this approach is too complex. Take a specific language and build a hardcoded editor for this language first. Only after you’ve built 2-3 successful editors, it makes sense to generalize and build a universal editor or an editor generator.
    7. Compilers shouldn’t be a black box, but expose the data structures as a public API surface.
    8. Syntax trees should be observable so that the editor can databind to them.
    9. Traditional expression editor should be hostable inside a structured editor for single-line statements and expressions.

    As a result of my work, I'm convinced that structured editors actually are, in some situations, more convenient than text editors and providing the programmer with two views on the code to choose from would be a benefit. Just like Visual Studio Class Designer - those who want to use it, well, just use it, and the rest continues to happily use the text editor. All these views should co-exist to provide the programmer with a richer palette of tools to chooce from.

    Hence, my first important conclusion. A program's internal representation (the AST) should be observable to allow the MVC architecture - many views on the same internal code model. With MVC, all views will be automatically kept in sync with the model. This is where for example something like WPF data-binding would come in handy.

    As for the structured editor itself - it is still a work in progress and I still hope to create a decent complement for text editors. It has to be usable and there are still a lot problems to solve before I can say: "Here, this editor is at least as good as the text editor". But I managed to solve so many challenging problems already, that I'm optimistic about the future.

    Current implementation

    The current implementation edits a substantial subset of C# 1.0 - namespaces, types, members (except events), and almost all statements. If you're interested, you can read more at http://www.guilabs.net and www.osenkov.com/diplom - those are two sites I built to tell the world about my efforts. I also accumulate my links about structured editing here: http://delicious.com/KirillOsenkov/StructuredEditors

    More languages

    It turned out that it makes sense to build structured editors not only for C#, but for other languages as well - XML, HTML, Epigram, Nemerle, etc. That is why, at the very beginning, the whole project was split in two parts - the editor framework and the C# editor built on top of it.

    Links

    1. http://structurededitor.codeplex.com
    2. http://guilabs.net
    3. http://www.osenkov.com/diplom
    4. http://delicious.com/KirillOsenkov/StructuredEditors

    If you want to know more, or if you want to share your opinion on this, please let me know. I welcome any feedback! Thanks!

    kick it on DotNetKicks.com Shout it
  • Kirill Osenkov

    UI without code or XAML: PropertyGrid, DataForm, etc.

    • 2 Comments

    WPF has certainly advanced the state-of-the-art in programming the UI. I personally think that WPF and Silverlight remove all the limits that existed to UI development in the past. The only limit now is your imagination. XAML is there for declarative machine-friendly UI descriptions, data-binding is for easier logic of syncing the UI to the data, automatic layout saves you all the trouble of aligning controls yourself, and so on.

    One thing that I notice though is that if your goal is a simple dialog or a wizard page, one is likely to write more code than is absolutely necessary, be it in a .NET language or XAML. For instance, one of the most trendiest patterns nowadays, MVVM, suggests that you have a model, a ViewModel (a UI-aware wrapper around model classes) and a View (that is databound to ViewModel). It is also suggested that you write some XAML to achieve what you need.

    My personal impression is that UI development nowadays has become complicated. It's super powerful, yes, but I find it is hard to find a simple solution for a simple scenario.

    For the purpose of this article, suppose that we need to implement a person editor dialog, and our business logic describes a person like this:

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    One is now likely to open XAML and start adding a Grid or a StackPanel with a couple of TextBoxes and databind them to the properties of the Person class. This approach is fine with me in general (since it decouples the UI from the domain model), however what I find is that it's just complicated and for simple scenarios might be an overkill.

    One other approach is often forgotten.

    PropertyGrid

    WinForms introduced an excellent control which unfortunately is probably less known and less used than it deserves: the PropertyGrid. You just add this control to your form and you just say:

    propertyGrid1.SelectedObject = joe;

    and you get:

    image

    What happens is that property grid reflects over the "editable" properties on the object, and displays each property as a separate row in the grid. Depending on the type of the property, it's value can be editable, additional controls can be displayed, for example, a color picker for colors, a calendar for DateTime, a checkbox for bool, etc. The nice thing about the design of the property grid (and I do think that the WinForms PropertyGrid is a very well designed control) is that if you have your own type, then you can also provide your own editor control for properties of that type.

    Also, the property grid provides certain other services - grouping properties into collapsible categories, description for selected property, multi-object selection (which enables setting a property on multiple objects simultaneously), etc.

    From the design perspective, what the property grid gives you is the ability to not duplicate the description of the UI. In the XAML example above you essentially describe your UI twice: first in your domain model (Name, Age) and then in your XAML (TextBox, TextBox) and then you bind the two together. With a property grid, on the contrary, you just declare your UI once, in your domain model, and you don't have to write any UI at all - property grid generates the UI for you.

    Unfortunately, this promising approach didn't go much further in the WinForms world, probably because of the limitations of the WinForms architecture (you couldn't re-style the property grid editors, rearrange rows or significantly customize its appearance (besides choosing the background and foreground colors and fonts).

    Silverlight 3 DataForm

    Thankfully, Silverlight 3 starts to fill the gap in the direction of eliminating the UI code by introducing the DataForm control: you can watch a great video by Mike Taulty about the DataForm here: http://beta.silverlight.net/learn/videos/silverlight-videos/dataform-control/ (and by the way, Mike Taulty makes excellent, excellent videos, highly recommended).

    Silverlight 3 DataForm comes with the free Silverlight Toolkit (http://silverlight.codeplex.com), is located in the assembly System.Windows.Controls.Data.DataFormToolkit.dll (GAC'ed) and works almost exactly like the WinForms PropertyGrid:

    image

    which results from this code:

    dataForm.CurrentItem = joe;

    I'm not aware of such a control for WPF but I haven't actually looked. All I know that it's a cool and promising approach which makes UI programming simpler, especially if you're designing dialogs, wizard pages or property grids.

    My own experiments

    Before Silverlight 3 came out, I was looking for an elegant way to implement property editing for the geometric figures in Live Geometry:

    image

    Since I didn't want to write any XAML for every property of every figure, I decided that the PropertyGrid design was a perfect fit, so I just implemented my own Property Grid (The benefit of having a hobby project is that you can use it as a playground and sandbox for experimenting with new ideas and approaches).

    The API is almost the same as the ones mentioned above:

    PropertyGrid.Show(this.Style, this.Drawing.ActionManager);

    gives you this:

    image

    Unlike the previous ones though, apart from the actual object being edited you can pass the second argument - a pointer to the ActionManager from my Undo Framework, which will make sure all the edits are recorded in the Undo history and can be undone.

    Metadata

    An important decision in the design of my property grid was to abstract away from modeling UI elements as CLR metadata. Both PropertyGrid and DataForm use CLR metadata (properties and their types) to encode what controls do we want to show on the form. Although metadata is very good for this (especially enriched with the .NET attributes as additional declarative mechanism, such as the [Description] attribute), I wanted to abstract away how the UI intent is declared, just like MEF can abstract away how a contract is specified. This was also inspired by the introduction of ICustomTypeDescriptor that allows extensibility of the PropertyGrid along the dimension of the property set. I didn't like metadata as the host language for the declaration of my UI elements, neither I liked XAML, for various reasons. So I came up with a basic interface called IValueProvider that encapsulates any value, be it a value of a CLR property or a value of a method's parameter, or anything else that might come up in the future. Here's a rough sketch (design not finalized yet):

    public interface IValueProvider
    {
        event Action ValueChanged;
        void RaiseValueChanged();
        T GetValue<T>();
        bool CanSetValue { get; }
        void SetValue<T>(T value);
        object Parent { get; }
        Type Type { get; }
        string Name { get; }
        string DisplayName { get; }
        T GetAttribute<T>() where T : Attribute;
        IEnumerable<T> GetAttributes<T>() where T : Attribute;
    }

    This gives me extensibility along the dimension of how UI elements are declared.

    Discovery

    To solve the task of taking content (think: an object) and extracting a set of editable values from it (think: properties), I introduced a so-called ValueDiscoveryStrategy. IncludeByDefaultValueDiscoveryStrategy will include all the properties unless they're marked with the [Ignore] attribute, and ExcludeByDefaultValueDiscoveryStrategy will exclude all the properties unless they're marked with the [PropertyGridVisible] attribute. Right now the discovery strategies only support CLR metadata (object properties and method parameters), but in the future nothing prevents me from adding more strategies to create editable values off of something else, say columns of a table in a database schema. This gives me the extensibility along the dimension of what properties to show in the grid.

    As an example, here's the ShapeStyle class that is being displayed in the screenshot above:

    public class ShapeStyle : LineStyle
    {
        public override FrameworkElement GetSampleGlyph() {...}
    
        Color mFill = Colors.Yellow;
        [PropertyGridVisible]
        public Color Fill
        {
            get
            {
                return mFill;
            }
            set
            {
                mFill = value;
                OnPropertyChanged("Fill");
            }
        }
    
        public override Style GetWpfStyle() {...}
    }

    The Fill property comes in here, and Color and Stroke width are inherited from LineStyle.

    Editors

    An editor is essentially a visual control that can edit an IValueProvider. For different types of values there are different kinds of editors. It's just a textbox for a string property, a checkbox for bools, a color picker for Color, etc. The nice thing (again, borrowed from the WinForms property grid design) is that the pool of editors is extensible. I use homemade dependency injection to discover all types of editors available for a type and instantiating a proper editor for a proper type. This gives me extensibility along the dimension of what types of properties can I edit.

    Also at this point kudos go to SilverlightContrib folks for an excellent ColorPicker control that I reused in my app! Great job and many thanks! BTW I fixed two bugs in it which I think I should submit as patches... need to remind myself later...

    Anyway, here's all it took to add an editor type for properties of type System.Windows.Color:

    public class ColorEditorFactory 
        : BaseValueEditorFactory<ColorEditor, Color> { }
    
    public class ColorEditor : LabeledValueEditor, IValueEditor
    {
        public ColorPicker Picker { get; set; }
    
        protected override UIElement CreateEditor()
        {
            Picker = new ColorPicker();
            Picker.SelectedColorChanging += ColorChanged;
            return Picker;
        }
    
        void ColorChanged(object sender, SelectedColorEventArgs e)
        {
            SetValue(e.SelectedColor);
        }
    
        public override void UpdateEditor()
        {
            Picker.SelectedColor = GetValue<Color>();
            Picker.IsEnabled = Value.CanSetValue;
        }
    }

    Complex types

    There are two approaches for displaying properties of complex types: either expanding them in place just like a tree view item gets expanded (and collapsed), or providing a hyperlink that, when clicked, will display that object's properties in the PropertyGrid, instead of the current one. In the latter case, one will probably want to implement some sort of a back button that will display the original object.

    Method Caller Buttons

    Finally, why not move it one step further? If we can get and set properties using this property grid, why not support calling methods? Here's a screenshot again of the polygon properties - note the three buttons at the bottom. They're generated too!

    image

    Here's the full source for the buttons:

    [PropertyGridVisible]
    public virtual void Delete() { ... }

    As you see, just add the [PropertyGridVisible] on any method and it will appear in the UI. Obviously, pushing the button will call the method.

    [PropertyGridVisible]
    [PropertyGridName("Create new style")]
    public void CreateNewStyle()
    {
        Drawing.ActionManager.SetProperty(this, "Style", 
            Drawing.StyleManager.CreateNewStyle(this));
        EditStyleButton();
    }
    [PropertyGridVisible]
    [PropertyGridName("Edit style")]
    public void EditStyleButton()
    {
        if (PropertyGrid != null)
        {
            PropertyGrid.Show(this.Style, this.Drawing.ActionManager);
        }
    }

    The next logical step is to allow calling methods with arguments. For example, having this method on your type:

    [PropertyGridVisible]
    public void AddEntry(Person person, DayOfWeek day, bool check)
    {
    }

    will result in this UI:

    image

    Clicking the button will call the method and pass the current values as arguments. This button is implemented as a simple button with PropertyGrid content that displays MethodInfo's parameters instead of object's property values (it uses a different ValueDiscoveryStrategy called ParameterDiscoveryStrategy).

    Summary

    Using this approach we can build a UI library for calling APIs. You design an API and you get a (basic) UI for it for free. This library will allow us to inspect any object at runtime similar to how debugger watch windows allow us to do it. Moreover, we can not only inspect it, but also set the property values and call methods on objects. This might prove useful not only for dialogs, wizard pages, property browsers, but possibly in other scenarios where you're editing a data structure directly and don't really care about customizing the default UI.

    I'm currently planning to continue evolving this prototype library as part of the Live Geometry source code, and possibly spawn off a separate project when this library becomes more mature and if there is demand.

    For now, if you're interested in the source code, you can find the up-to-date implementation at http://livegeometry.codeplex.com/SourceControl/ListDownloadableCommits.aspx -> Main\DynamicGeometryLibrary\PropertyGrid.

    Let me know if you have any questions or feedback. Thanks!

  • Kirill Osenkov

    www.officelabs.com and Garage: How Microsoft Supports Grassroots Innovation

    • 0 Comments

    This post was originally aimed for Microsoft employees who also have a side project, or a hobby project. It turns out, we have a nice internal thing called “The Garage” that is aimed to specifically support and foster such “evenings- and weekends projects” by Microsoft employees.

    Garage: What they do
    I own a side project (plug: http://livegeometry.codeplex.com) and Garage did a free usability study for it, which was really awesome. They organized everything (including free food), invited participants, prepared the task lists and helped to actually conduct the usability study. This was a great experience – I actually watched three MS employees work with Live Geometry and listen to their feedback, thoughts, comments as they discover and use the software.

    Usability study

    I realized that Live Geometry is still far from being intuitive and there are a lot of things that I can improve. I’ve gathered a lot of valuable information which I was able to convert to more than 50 actionable bugs! Another useful experience that I gained is how to conduct a good usability study. I've learned the following:

    • Be friendly and thankful for the participant's time. They're doing you a favor.
    • It's not a test for the participant's skills, it's a test for the usability of the software.
    • Don't talk, don't reveal how things work, don't answer questions too early.
    • Don't let them struggle too much, help them out when they're really stuck.
    • The participant is always right and your software is always wrong :)
    • Whatever feedback they give is good feedback.
    • Don't forget to write things down.
    • Show them how it's supposed to work at the end, it's likely you'll be rewarded with a "wow" :)

    Other Garage events

    Garage organizes a range of other events: Stay Late and Code (pizza provided), Improve a Project (where they demo projects and gather user feedback), Speed-dating for innovators (they bring together the folks who need help on a project and folks who would like to participate in a project or help out), help with hosting a project, etc.

    Productivity Science Fair

    Also recently I participated in a semi-annual company-wide exhibition called the Productivity Science Fair. It generated a lot of interest and was very crowded (actually, a lot of people stopped by my booth, wanted to learn more about my project and left their contact info - I ended up collecting more than 50 e-mail addresses of those who were interested!). I literally never spend more than one minute without someone stopping by, almost lost my voice at the end of the day. But it was so much fun!

    So, if you’re a Softee AND have a side project or projects, do check out http://garage and/or add yourself to the ‘garage’. At this point – huge thanks to Quinn Hawkins and Jennifer Michelstein for their engagement!

    What’s there for non-Microsofties? www.officelabs.com

    I wouldn’t blog about this at all if there wasn’t some goodness for folks external to Microsoft. Well, guess what, some of those side projects eventually become external so you can benefit too! Check out http://www.officelabs.com, especially the Grassroots Innovation projects: http://www.officelabs.com/Pages/Grassroots.aspx?category=grassroots for a sample of several projects already out there. Garage is actually sponsored by Office Labs and it's nice to see innovation being fostered both internally and externally.

    Microsoft Education Labs - www.educationlabs.com

    One other thing Quinn from the Garage team was helping me with is getting in touch with folks from Microsoft Education. I didn't know it, but there is a site called www.educationlabs.com, which is similar to the Office Labs innovation site, but specifically aimed at educational software and products for students and teachers. I might be working with these guys to see if we can collaborate to release Live Geometry as educational software for schools. That would be really cool!

    Semblio - digital learning from Microsoft

    Last, but not least, at the Productivity Science Fair I've met folks from Semblio, which is a really interesting product I didn't know about. Here's a quote (read more here):

    Now you can make your instructional materials even more valuable. Microsoft Semblio provides easy access to the power of Microsoft .NET and Windows Presentation Foundation (WPF) by tailoring the Microsoft development platform specifically to the education market. Get ready to create an immersive education content experience.

    Essentially, they leverage WPF to create rich interactive learning materials. We've met with the Semblio team and they were really excited to learn about Live Geometry. They were particularly happy that it's easy to create a WPF User Control hosting a geometry drawing and that I use XML as the serialization format, because this way it's super easy to integrate Live Geometry content with the Semblio framework.

  • Kirill Osenkov

    Calling new on an interface

    • 10 Comments

    Interesting thing: technically there is a way to call new on an interface to create an object. How? Using a feature in the C# compiler for COM-interop support:

    using System.Runtime.InteropServices;
    
    class Program
    {
        static void Main(string[] args)
        {
            IFoo foo = new IFoo();
        }
    }
    
    class Foo : IFoo
    {
    }
    
    [ComImport]
    [Guid("DC1CB768-0BE5-4200-8D0A-C844BFBE3DE7")]
    [CoClass(typeof(Foo))]
    interface IFoo
    {
    }

    Here you specify that Foo is a CoClass for the interface IFoo using the three attributes CoClass, ComImport and Guid. It does not matter that no real COM objects are involved, C# compiler is fine with that. What it does, it replaces the call to the IFoo() "constructor" to the equivalent constructor on the co-class Foo.

    Interestingly enough, Foo doesn't have to even implement IFoo - the program will compile just fine and it will create an instance of type Foo at runtime, but it will fail when we try to put an object of type Foo into a local variable of type IFoo.

    It's yet another way to instantiate a type without mentioning it in source code. As such, it can potentially be a way to achieve what factory methods do - instead of mentioning the concrete type in instantiations all over your code, you can just have a centralized place where you say what type to instantiate. With this you can easily substitute the concrete type via the CoClass attribute.

    However, this is not as powerful as factory methods (you have to recompile your app to change concrete class and you can't have multiple concrete types at the same time).

    I wouldn't encourage using this stuff anyway because this will probably confuse readers who read your source. But despite of anything, this *is* an interesting technique.

  • Kirill Osenkov

    Visual Studio disappears when creating a Silverlight 3 Application

    • 2 Comments

    I have Visual Studio 2008 SP1 and Silverlight 3 tools on the laptop I’m writing this post on. Ten minutes ago I was trying to create a new Silverlight 3 application through the New Project Dialog and after creating the project Visual Studio just disappeared on me.

    Usually when VS disappears instantly without the Watson dialog this means something really serious has happened, like a stack overflow, or an internal CLR exception.

    I was almost going to log in to work to get the symbols and sources and start debugging, but doing a web search beforehand turned out to be a good idea. Indeed – it turns out to be a known bug in the CLR execution engine, serious enough so that we even released a hotfix for it:

    You know that you’re seeing this issue if the Windows Application Error log contains the entry ID 1023:

    .NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (6FC85E00) (80131506)

    Installing the hotfix 963676 from this location https://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=16827 helped to resolve the problem.

    If you ran into this – sorry for the inconvenience!

  • Kirill Osenkov

    5 min. screencast: Live Geometry overview

    • 28 Comments

    Microsoft sponsored a usability study for my side project Live Geometry, and I have to say, it was awesome. It was a lot of fun watching the participants using the software and I got a ton of great and useful feedback.

    I have to confess, I didn’t realize that it’s not obvious how to use Live Geometry (especially if you’ve never seen it before). Since I was the one who developed the software, I subconsciously assumed that it’s all intiutive and trivial. Well guess what, it turns out to be not the case. I am not the end user. Things that are obvious for me, might not be obvious for others.

    So I developed a plan on how to make things better. There are two ways: improving User Experience and investing in User Education. The former will be a slow and gradual process of me designing the features and the UI, fixing bugs, reworking the UI and thinking through UI details.

    Today I’ll start approaching the task of User Education and present a 5 min. screencast – a brief overview of the Live Geometry software and its possibilities (Hint: double-click the video for fullscreen viewing):

    Get Microsoft Silverlight

    You can also download the .wmv file (15 MB).

    More documentation will follow later, but this should at least give a quick start and give you an idea of how things work.

    Any feedback is welcome!

  • Kirill Osenkov

    All C# Compiler Developer Team blogs

    • 2 Comments

    With Ian Halliday, a developer on the C# Compiler team who started to blog recently, all of the C# compiler devs are blogging! Here’s the list of their blogs sorted alphabetically:

  • Kirill Osenkov

    Instantiating types with no public constructors

    • 7 Comments

    It turns out, Activator.CreateInstance and Activator.CreateInstance<T> fail if there is no public parameterless constructor defined on a type we’re trying to instantiate. Even if the constructor is internal (basically, anything other than public), CreateInstance will fail. This one was a surprise actually, I would expect the reflection binder to work for internal constructors at least.

    Update: it turns out, there is an overload of Activator.CreateInstance(Type, bool) that does exactly what I want. Don’t use what I posted below :) Thanks to Andrey Shchekin for the tip!

    Nevertheless, a more powerful alternative to Activator.CreateInstance in this case is to find the non-public constructor and invoke it manually:

    using System;
    using System.Reflection;
    
    class Test
    {
        private Test() { }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance;
            var ctor = typeof(Test).GetConstructor(flags, null, new Type[0], null);
            var instance = ctor.Invoke(null);
    
            //var instance = Activator.CreateInstance<Test>(); // Exception: No parameterless constructor defined for this object.
            //var instance = Activator.CreateInstance(typeof(Test)); // Exception: No parameterless constructor defined for this object.
        }
    }

    Why do I need this? Well, there is a class in our codebase that everyone was instantiating all over the place. But this class should have inherently been a singleton. I changed the code all over the place to use a singleton instead of instantiating it and I wanted to prohibit people to instantiate this class in the future.

    We have a little Singleton helper that essentially looks like this:

    public class Singleton<T> where T : class
    {
        static T instance;
        public static T Instance
        { 
            get
            {
                if (instance == null)
                {
                    instance = Instantiate();
                }
                return instance;
            }
        }
    
        static T Instantiate()
        {
            return Activator.CreateInstance<T>();
        }
    }

    So I would just inherit the class that everyone was using from Singleton like this: CommonClass : Singleton<CommonClass> and make the constructor private so that people can’t instantiate it manually anymore. However this became a problem because the Singleton’s Instantiate() method failed for non-public constructors. Now that I’ve used the approach above, it works fine. Singleton can instantiate the class, but no one else can.

     

    P.S. Yes, I know about the right way to implement a singleton, I know about double-check locking and threading and that reflection is bad. But this solves the problem.

    P.P.S. Yes, I know about burning the base class and that mixing in a singleton via inheritance is generally a bad idea. It works for us and does it’s job.

    P.P.P.S. It occurred to me that if we had extension properties, one could have just made Instance an extension property on every type (that implements a certain “marker” interface). But there is no way currently to mix-in state into existing types (if you don’t look at WPF and their attached properties and dependency properties).

  • Kirill Osenkov

    Comparing doubles can produce unexpected results

    • 4 Comments

    Well, guess what, smart people learn from other people’s mistakes and Kirill learns from his own.

    This is actually a well-known caveat about doubles, but still a reminder about something to be aware of. A double value can be something else than you might think it is. For example, when you expect a double to be exactly 6, it could be 5.9999999999999991 and you will wonder, how on earth is it possible that 6 != 6:

    image

    The upper tooltip clearly shows that the second coordinate is 6, but comparing it with 6 fails. Whoa, the detailed view shows 5.9999999999999991.

    What’s up with that? Luckily, the .NET framework source is easily available, so a quick look at Point.ToString() reveals that they simply format the output to round away the last couple of precision digits. The X and Y on the contrary are displayed unformatted (or should I say formatted less aggressively).

    Under closer examination (and after half an hour of pulling my hair out) it looks like the system represented the calculation result as close to the decimal integer 6 it could, given the double precision in .NET encoded in binary. The failing code was comparing if (point.Y == 6) and the comparison failed against my expectations.

    The solutioin for this is to test for the fact, “is the value within epsilon of the ideal value of 6”, like this: if (Math.Abs(point.Y – 6) < 0.00000001) …

    I should have read more Eric back in school.

  • Kirill Osenkov

    Having Fun with the New Editor in VS 2010

    • 6 Comments

    I was figuring out how to test the new WPF editor through the new managed API and it suddenly occurred to me how easy it is to do things to the editor that just weren’t possible before. For example, I decided that I like my editor rotated:

    image

    Why? Because I can!

    public void RotateEditor(int degrees)
    {
        var textView = GetWpfTextView();
        textView.VisualElement.LayoutTransform = new RotateTransform(degrees);
    }

    What amazed me is that it continued to work just fine – I was expecting to find a ton of bugs this way, but things just continued to work seamlessly. And my test did this to the running instance of Visual Studio without even changing anything – I injected the above method in the VS main AppDomain and ran it on a currently opened document.

    Apart from meaningless entertainment “just for fun” you can do so much more useful stuff. For example, it’s super easy to insert images right into the editor:

    imageinsertion_01.png

    A friend of mine will soon be publishing a spell-checker add-in for XML comments that was very easy to write.

    You can find more samples and information about the new editor at the following locations:

    And finally, don’t forget to follow the New Editor on Twitter: http://twitter.com/vseditor

  • Kirill Osenkov

    Bling: a WPF Framework/Declarative Strongly-Typed DSL for Quick Expressive C# WPF Apps

    • 0 Comments

    Several weeks ago I met with Sean McDirmid from the Microsoft’s Research and Prototyping facility in Beijing to chat about IDE design and his recent projects. Sean is a well-known researcher with broad interests in languages, compilers, and, recently, WPF and graphics. He was demoing the (open-source) project he’s working on now: http://bling.codeplex.com. Here are some quotes from the project’s website:

    Bling is a C#-based library for easily programming images, animations, interactions, and visualizations on Microsoft's WPF/.NET. Features include:

      • Declarative constraints that maintain dynamic relationships in the UI without the need for complex event handling. For example, button.Width = 100 - slider.Value causes button to shrink as the slider thumb is moved to the right, or grow as it is moved to the left. Constraints have many benefits: they allow rich custom layouts to be expressed with very little code, they are easy animate, and they support UIs with lots of dynamic behavior. [Kirill: note that this is directly in C# with all the type checking! Think F# Units of Measure.]
      • Simplified animation with one line of code. For example, button.Left.Animate.Duration(500).To = label.Right will cause button to move to the right of label in 500 milliseconds. [Kirill: the magic of implicit conversions, operator overloading, extension methods and expression trees working together!]
      • Pixel shader effects without the need to write HLSL code or boilerplate code! For example, canvas.CustomEffect = (input, uv) => new ColorBl(new Point3DBl(1,1,1) - input[uv].ScRGB, input[uv].ScA); defines and installs a pixel shader on a canvas that inverts the canvas's colors. Pixel shading in Bling takes advantage of your graphics card to create rich, pixel-level effects. [Kirill: they do code-gen for this, I think by just spitting out C# code, not sure though.]
      • Support for multi-pass bitmap effects such as diffuse lighting.
      • An experimental UI physics engine for integrating physics into user interfaces! The physics supported by Bling is flexible, controllable, and easy to program.
      • Support for 2.5D lighting.
      • A rich library of geometry routines; e.g., finding where two lines intersect, the base of a triangle, the area of triangle, or a point on Bezier curve. These routines are compatible with all of Bling's features; e.g., they can be used in express constraints, pixel shaders, or physical constraints. Bling also provides a rich API for manipulating angles in both degrees and radians. [Kirill: Competition! Need to take a look at this and Live Geometry side-by-side, maybe we can benefit from each other’s work.]
      • And many smaller things; e.g., a frame-based background animation manager and slide presentation system. [Kirill: yeah, Sean did his demo in his own WPF app – no PowerPoint. Too bad he had to recompile it to fix a typo :)]
      • As a lightweight wrapper around WPF, Bling code is completely compatible with conventional WPF code written in C#, XAML, or other .NET languages [Kirill: and Silverlight].

    Essentially, they use a similar trick to what F# did with Units of Measure – they leverage the type system to represent strongly typed “units”, wrap types such as System.Double and Point using implicit conversions and use operator overloading, extension methods and more to create an expressive DSL for representing constraints, math formulas, etc. directly within the host language (C#). Bling also makes heavy use of expression trees to do intraspection and meta-programming – using C# expressions to capture the formula as opposed to capturing the value. After a quick glance at the source code, I also notice some DLR usage and code-generation techniques.

    What can we do with it? Well, Sean mentioned that this is great for rapid prototyping in C#, without ever using XAML. This framework is somewhat different from the WPF style, but it definitely looks interesting and champions what I think is a great collection of coding tricks cleverly combined into DSLs. Also, if you download and build the demo, it’s REALLY IMPRESSIVE. I don’t know about you, but I just love those eye-candy demos with bright colors, animations, gradients and other effects.

    Here are a couple screenshots for a start. For more, take a look at the Bling tutorial.

    image

    c0.jpg

    image

    a_distortB.jpg

    metaball.jpg

    Have fun!

  • Kirill Osenkov

    Silverlight 3 is out!

    • 0 Comments

    “Well, unless you’ve been living under a rock…” © CyrusN :)

    I’m very excited about Silverlight 3 which has TONS of new awesome features, from better graphics and text to out-of-browser support, style improvements and… drumroll… SaveFileDialog (finally) :)

    Links:

  • Kirill Osenkov

    http://silverlight.live.com

    • 0 Comments

    http://silverlight.live.com (Microsoft Silverlight Streaming) is a free service from Microsoft to host your Silverlight applications and videos. You can upload your .xap or .wmv files and reference them from any websites, blogs, etc. My favorite part is that you get 10 GB in free storage, with no ads, no strings attached. Also, they give you high scalability and availability – the media is hosted “in the cloud” that can handle a lot of traffic. Finally, you have a nice admin site where you can manage your account, videos and applications – you can upload new videos, applications, track usage (number of downloads or video views), etc.

    The MSDN Silverlight Streaming Samples page contains several nice Silverlight samples. I use http://silverlight.live.com to host http://livegeometry.com and my other applications and videos. Enjoy!

  • Kirill Osenkov

    Samples for the Undo Framework

    • 13 Comments

    I just added some samples for the Undo Framework. You can find the samples in the source code or download them from the project website.

    MinimalSample

    First is a simple Console App sample called MinimalSample. Here’s the full source code:

    using System;
    using GuiLabs.Undo;
    
    namespace MinimalSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Original color");
    
                SetConsoleColor(ConsoleColor.Green);
                Console.WriteLine("New color");
    
                actionManager.Undo();
                Console.WriteLine("Old color again");
    
                using (Transaction.Create(actionManager))
                {
                    SetConsoleColor(ConsoleColor.Red); // you never see Red
                    Console.WriteLine("Still didn't change to Red because of lazy evaluation");
                    SetConsoleColor(ConsoleColor.Blue);
                }
                Console.WriteLine("Changed two colors at once");
    
                actionManager.Undo();
                Console.WriteLine("Back to original");
    
                actionManager.Redo();
                Console.WriteLine("Blue again");
                Console.ReadKey();
            }
    
            static void SetConsoleColor(ConsoleColor color)
            {
                SetConsoleColorAction action = new SetConsoleColorAction(color);
                actionManager.RecordAction(action);
            }
    
            static ActionManager actionManager = new ActionManager();
        }
    
        class SetConsoleColorAction : AbstractAction
        {
            public SetConsoleColorAction(ConsoleColor newColor)
            {
                color = newColor;
            }
    
            ConsoleColor color;
            ConsoleColor oldColor;
    
            protected override void ExecuteCore()
            {
                oldColor = Console.ForegroundColor;
                Console.ForegroundColor = color;
            }
    
            protected override void UnExecuteCore()
            {
                Console.ForegroundColor = oldColor;
            }
        }
    }

    Here we define a new action called SetConsoleColorAction, and override two abstract methods: ExecuteCore() and UnExecuteCore(). In the ExecuteCore(), we change the color to the new color and backup the old color. In UnExecuteCore() we rollback to the backed up old color. We pass the action all the context information it needs (in our case, the desired new color). We rely on the action to backup the old color and store it internally.

    The philosophy is to only store the smallest diff as possible. Try to avoid copying the entire world if you can only save the minimal delta between states.

    Next, pay attention to the SetConsoleColor method. It wraps creating the action and calling RecordAction on it. It helps to create an API that abstracts away the action instantiation so that it is transparent for your callers. You don’t want your callers to create actions themselves every time, you just want them to call a simple intuitive API. Also, if for whatever reason you’d like to change or remove the Undo handling in the future, you’re free to do so without breaking the clients.

    Finally, the source code in Main shows how you can intersperse your API calls with calls to Undo and Redo. It also shows using a transaction to group a set of actions into a single “multi-action” (Composite design pattern). You can call your API within the using statement, but the actions’ execution is delayed until you commit the transaction (at the end of the using block). That’s why you don’t see the console color changing to red in the middle of the block. If you undo a transaction, it will undo all the little actions inside it in reverse order.

    WinFormsSample

    The second sample is called WinFormsSample. It shows a windows form that let’s you edit properties of a business object:

    image

    You can change the text of both name and age, and the values will be mapped to the business object. You can also “Set Both Properties” which illustrates transactions. Then you can click Undo and it will rollback the state of your object to the previous state. The UI will update accordingly.

    There is a trick in the code to avoid infinite recursion: on textbox text change, update the business object, fire an event, update the textboxes, update the business object again, etc... We use a boolean flag called “reentrancyGuard” that only enables the TextChanged events if the textbox modification was made by user, and not programmatically. If we updated the textboxes as a results of the business object change, no need to update the business object.

    Note: If this was WPF, I would just use two-way data binding, but I wanted to keep the sample as simple as possible and use only basic concepts.

    Action merging

    Another thing worth mentioning that this sample demonstrates is action merging. As you type in the name in the textbox ‘J’, ‘o’, ‘e’, you don’t want three separate actions to be recorded, so that you don’t have to click undo three times. To enable this, an action can determine if it wants to be merged with the next incoming action. If the next incoming action is similar in type to the last action recorded in the buffer, they merge into a single action that has the original state of the first action and the final state of the new action. This feature is very useful for recording continuous user input such as mouse dragging, typing and other events incoming at a high rate that you want to record as just one change.

    We update the visual state of the Undo and Redo buttons (enabled or disabled) to determine if the actionManager can Undo() or Redo() at the moment. We call the CanRedo() and CanUndo() APIs for this.

    Hopefully this has been helpful and do let me know if you have any questions.

  • Kirill Osenkov

    New CodePlex project: a simple Undo/Redo framework

    • 57 Comments

    I just created a new CodePlex project: http://undo.codeplex.com

    What

    It's a simple framework to add Undo/Redo functionality to your applications, based on the classical Command design pattern. It supports merging actions, nested transactions, delayed execution (execution on top-level transaction commit) and possible non-linear undo history (where you can have a choice of multiple actions to redo).

    The status of the project is Stable (released). I might add more stuff to it later, but right now it fully satisfies my needs. It's implemented in C# 3.0 (Visual Studio 2008) and I can build it for both desktop and Silverlight. The release has both binaries.

    Existing Undo/Redo implementations

    I do realize that my project is the reinvention of the wheel at its purest, existing implementations being most notably:

    However I already have three projects that essentially share the exact same source code, so I decided that it would be good to at least extract this code into a reusable component, so perhaps not only me but someone else might find it useful too.

    It's open-source and on CodePlex, so I also have a chance of benefiting from it if someone contributes to it :)

    History

    It all started in 2003 when I first added Undo/Redo support to the application that I was developing at that time. I followed the classical Command design pattern, together with Composite (for nested transactions) and Strategy (for plugging various, possibly non-linear undo buffers).

    Then I needed Undo/Redo for my thesis, so I just took the source code and improved it a little bit. Then I started the Live Geometry project, took the same code and improved it there a little bit, fixing a couple of bugs. Now the mess is over, and I'm finally putting the code in one place :)

    A good example of where this framework is used is the Live Geometry project (http://livegeometry.codeplex.com). It defines several actions such as AddFigureAction, RemoveFigureAction, MoveAction and SetPropertyAction.

    Actions

    Every action encapsulates a change to your domain model. The process of preparing the action is explicitly separated from executing it. The execution of an action might come at a much later stage after it's been prepared and scheduled.

    Any action implements IAction and essentially provides two methods: one for actually doing the stuff, and another for undoing it.

    /// <summary>
    /// Encapsulates a user action (actually two actions: Do and Undo)
    /// Can be anything.
    /// You can give your implementation any information it needs to be able to
    /// execute and rollback what it needs.
    /// </summary>
    public interface IAction
    {
        /// <summary>
        /// Apply changes encapsulated by this object.
        /// </summary>
        void Execute();
    
        /// <summary>
        /// Undo changes made by a previous Execute call.
        /// </summary>
        void UnExecute();
    
        /// <summary>
        /// For most Actions, CanExecute is true when ExecuteCount = 0 (not yet executed)
        /// and false when ExecuteCount = 1 (already executed once)
        /// </summary>
        /// <returns>true if an encapsulated action can be applied</returns>
        bool CanExecute();
    
        /// <returns>true if an action was already executed and can be undone</returns>
        bool CanUnExecute();
    
        /// <summary>
        /// Attempts to take a new incoming action and instead of recording that one
        /// as a new action, just modify the current one so that it's summary effect is 
        /// a combination of both.
        /// </summary>
        /// <param name="followingAction"></param>
        /// <returns>true if the action agreed to merge, false if we want the followingAction
        /// to be tracked separately</returns>
        bool TryToMerge(IAction followingAction);
    
        /// <summary>
        /// Defines if the action can be merged with the previous one in the Undo buffer
        /// This is useful for long chains of consecutive operations of the same type,
        /// e.g. dragging something or typing some text
        /// </summary>
        bool AllowToMergeWithPrevious { get; set; }
    }

    Both methods share the same data required by the action implementation and are supplied when you create an action instance.

    ActionManager

    Your domain model (business objects) will likely have an instance of ActionManager that keeps track of the undo/redo buffer and provides the RecordAction(IAction) method. This method adds an action to the buffer and executes it. And then you have ActionManager.Undo(), ActionManager.Redo(), CanUndo(), CanRedo() and some more stuff.

    As a rule, the thing that works for me is that I generally have two APIs: one that is public and lazy (i.e. it just creates an action and adds it to the buffer), and the other which is internal and eager, that does the actual work. Action implementation just calls into the eager API, while the public API is lazy and creates actions transparently for the consumer.

    History

    Right now I only have a SimpleHistory. Instead of having two stacks, I have a state machine, where Undo goes to the previous state and Redo goes to the next state, if available. Each graph edge stores an action (implementation of IAction). As the current state transitions along the graph edge, IAction.Execute or UnExecute is being called, depending on the direction in which we go (there is a logical "left" and "right" in this graph, which kind of represents "future" and "past").

     

    image

    It's possible for this linked list to become a tree, where you try something out (way1), don't like it, undo, try something else (way2), like it even less, undo, and choose to go back and redo way1. However this is not implemented yet.

    Transactions

    Transactions are groups of actions viewed as a single action (see Composite design pattern).

    Here's a typical usage of a transaction:

    public void Add(IEnumerable<IFigure> figures)
    {
        using (Transaction.Create(ActionManager))
        {
            figures.ForEach(Add);
        }
    }

    If an action is recorded while a transaction is open (inside the using statement), it will be added to the transaction and executed only when the top-level transaction commits. This effectively delays all the lazy public API calls in the using statement until the transaction commits. You can specify that the actions are not delayed, but executed immediately - there is a corresponding overload of Transaction.Create specifically for that purpose.

    Note that you can "misuse" this framework for purposes other than Undo/Redo: one prominent example is navigation with back/forward.

    Update: I just posted some samples for the Undo Framework: http://blogs.msdn.com/kirillosenkov/archive/2009/07/02/samples-for-the-undo-framework.aspx

  • Kirill Osenkov

    Visual Studio 2010 Beta1 + TFS + HTTPS (TF31001): The ServicePointManager does not support proxies with the https scheme.

    • 1 Comments

    This is just a little note to myself and others who might run into this. I was using Visual Studio 2010 and Team Foundation Client to access a CodePlex project over HTTPS (port 443), and got this error message:

    ---------------------------
    Microsoft Visual Studio
    ---------------------------
    Microsoft Visual Studio

    TF31001: Cannot connect to Team Foundation Server at tfs07.codeplex.com. The server returned the following error: The ServicePointManager does not support proxies with the https scheme.
    ---------------------------
    OK   Help  
    ---------------------------

    By the way, did you know that you can press Ctrl+C to copy the contents of a message box dialog to clipboard? (Well, at least in Visual Studio message boxes).

    Anyway, it turns out this is a known bug: https://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=453677

    The workaround so far is to create a couple of string values in the registry:

    This problem it seams is to do with the way Visual Studio 2010 connects to your TFS server over HTTPS. The default value for “BypassProxyOnLocal” in Visual Studio 2008 was “False”, but it has been changed to “True” for Visual Studio 2010 Beta 1.

    You can fix this by adding the following registry keys and restarting Visual Studio 2010:

    You need to add a “RequestSettings” key to both of the following location that contains a string value pair of “BypassProxyOnLocal=’False’”.

    32bit OS Key Locations:
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\TeamFoundationServer\10.0\RequestSettings
    HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\10.0\TeamFoundation\RequestSettings

    64bit key locations:
    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\TeamFoundationServer\10.0\RequestSettings
    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\TeamFoundation\RequestSettings

    How to: Change the BypassProxyOnLocal Configuration: http://msdn.microsoft.com/en-us/library/bb909716(loband).aspx

    Update: I just noticed Aaron Block has also blogged about this.

  • Kirill Osenkov

    VS Project, C++ and Editor team blogs

    • 0 Comments

    This is just a quick announcement about some Visual Studio team blogs that might be really worth checking out.

  • Kirill Osenkov

    Algorithms in C#: shortest path around a polygon (polyline routing)

    • 14 Comments

    Suppose you have to build a road to connect two cities on different sides of a lake. How would you plan the road to make it as short as possible?

    To simplify the problem statement, a lake is sufficiently well modeled by a polygon, and the cities are just two points. The polygon does not have self-intersections and the endpoints are both outside the polygon. If you have Silverlight installed, you can use drag and drop on the points below to experiment:

    Get Microsoft Silverlight

    Solution description

    A shortest path between two points is a segment that connects them. It’s clear that our route consists of segments (if a part of the path was a curve other than a segment, we could straighten it and get better results). Moreover, those segments (which are part of the route) have their endpoints either on polygon vertices or the start or end point. Again, if this were not the case, we would be able to make the path shorter by routing via the nearest polygon vertex.

    Armed with this knowledge, let’s consider all possible segments that connect the start and end point and all polygon vertices that don’t intersect the polygon. Let’s then construct a graph out of these segments. Now we can use Dijkstra’s algorithm (or any other path finding algorithm such as A*) to find the shortest route in the graph between start and endpoints. Note how any shortest path algorithm can essentially boil down to a path finding in a graph, because a graph is a very good representation for a lot of situations.

    From the implementation perspective, I used my dynamic geometry library and Silverlight to create a simple demo project that lets you drag the start and end points as well as polygon vertices. You can also drag the polygon and the plane itself. I also added rounded corners to the resulting path and made it avoid polygon vertices to make it look better.

    Here is the source code for the sample. Here’s the main algorithm. It defines a data structure to describe a Graph that provides the ShortestPath method, which is the actual implementation of the Dijkstra’s algorithm. ConstructGraph takes care of adding all possible edges to the graph that do not intersect our polygon. SegmentIntersectsPolygon also determines what the name suggests.

    I hope to post more about polygon routing in the future and do let me know if you have any questions.

  • Kirill Osenkov

    yield return and Continuation-Passing Style

    • 5 Comments

    Someone was recently porting some C# code to VB and had a question about how to convert the C# yield return iterator methods to VB (VB currently doesn’t support iterators).

    There were a lot of replies like “use Reflector on a compiled binary and copy-paste the generated state machine code”. The problem with the Reflector approach is that you go one step down the abstraction ladder and lose the high-level intent expressed in the original code. Resulting code will be surely harder to read and maintain.

    Surprisingly, no one mentioned CPS. But before applying continuation-passing style, let’s first look at the nature of yield return. It’s essentially a producer-consumer model where the producer is a state machine where transitions are triggered by the MoveNext calls and current state is saved in the Current property. On the consumer side there is eventually almost always a foreach loop with some logic in the body, and this logic only requests the next element (and triggers a state machine transition) after it’s done processing the current element.

    It turns out, we can preserve the algorithm encoded in the iterator and avoid using yield return and thus having the compiler to generate the state machine code for us. To achieve this, we pass the logic that used to be in the consumer foreach loop (a continuation) directly into the iterator.

    Here’s an example with yield return that we want to convert:

    using System;
    using System.Collections.Generic;
    
    class Node<T>
    {
        public Node<T> Left { get; set; }
        public T Value { get; set; }
        public Node<T> Right { get; set; }
    
        public IEnumerable<T> Traverse()
        {
            if (Left != null)
            {
                foreach (var item in Left.Traverse())
                {
                    yield return item;
                }
            }
            yield return Value;
            if (Right != null)
            {
                foreach (var item in Right.Traverse())
                {
                    yield return item;
                }
            }
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Node<int> tree = new Node<int>()
            {
                Left = new Node<int>()
                {
                    Value = 1,
                    Right = new Node<int>()
                    {
                        Value = 2
                    }
                },
                Value = 3,
                Right = new Node<int>()
                {
                    Value = 4
                }
            };
    
            foreach (var item in tree.Traverse())
            {
                Console.WriteLine(item);
            }
        }
    }

    Now, the trick is to pass the “continuation”, which is the code that processes the results, directly into the iterator method (using first-class functions AKA delegates):

    public IEnumerable<T> Traverse()
    {
        List<T> result = new List<T>();
        TraverseInner(this, result.Add);
        return result;
    }
    
    void TraverseInner(Node<T> root, Action<T> collector)
    {
        if (root == null) return;
        TraverseInner(root.Left, collector);
        collector(root.Value);
        TraverseInner(root.Right, collector);
    }

    Note how we created an internal helper that actually does the traversing and how the logic of the traversal is even shorter than in the original method. We don’t use yield return and still maintain a high level of abstraction. Where was yield return, now is a call to the helper method. Otherwise, the control flow is the same.

    The downside of this approach though is that we lose laziness, which means, that once requested, we eagerly calculate all the results and return them at once. This is the price that we pay for losing the state machine that can store intermediate results for us.

    If we remove the limitation of having to return IEnumerable<T>, we can directly consume the helper method without having to write a foreach loop:

    TraverseInner(tree, Console.WriteLine);

    Here we’re passing the “continuation” (which is the Console.WriteLine method) directly inside the iterator. Note how the consumer side became shorter as well because we don’t have to write a foreach loop.

    Note: a while ago I blogged about yield foreach which would allow to get rid of foreach statements in the iterator scenario as well.

    Note 2: I’m guessing it’s possible to get rid of yield return and still keep the laziness, I just need to do more homework on Push LINQ and similar to find a nice solution to this.

  • Kirill Osenkov

    Some resources about Visual Studio Extensibility

    • 1 Comments

    A couple of readers have posted questions about Visual Studio Extensibility, DTE, your own packages, commands, experimental hive etc. To be frank, I’m not an expert in this field, so instead of trying to answer these questions, I will point to some better resources for VSX (VS Extensibility):

Page 4 of 7 (153 items) «23456»