The Stochastic Game

Ramblings of General Geekery

Posts with tag 'csharp'

    The extension method trick

    If you’ve been writing C# code lately you should be pretty familiar with extension methods: it’s a nice compiler feature added to C# 3.0 which lets you “attach” methods to an existing type. So for instance, if you define the following extension method: static class ConsoleExtensions { public static void WriteReversed(this TextWriter writer, string message) { writer.WriteLine(new string(message.Reverse().ToArray())); } } You can write:
    Read more...

    IEnumerable is awesome

    I’ve always thought that one of the most underrated features of C# is the yield statement and its companion, IEnumerable<T>. It may be because I’m working a lot with people coming from an exclusively C++ background – it takes some time to adapt to a new language with new paradigms, especially when that language can look a lot like “C++ without delete!” at first. But there are so many wonderful constructs in C# (especially in the past couple versions) that it’s a shame when people keep writing code “the old way”…
    Read more...

    Making WPF controls double-clickable

    A common UI pattern features the ability to double-click on a control to go in “edit” mode. So for example, you have a TextBlock that shows you the name of an object, and you can double-click it to change it into a TextBox where you can edit that name. At this point, it’s easy to hook up the MouseDoubleClick event, or some other mouse event, but that’s not very MVVM-like, is it?
    Read more...

    Xaml serialization quirks and gotchas

    I recently had to build a little tool that would read its configuration from a XAML file (because XAML serialization is, most of the time, better and more customizable than standard XML serialization). The trick was that this tool had to be built on top of .NET 3.0 – not 3.5 or 4.0. And I discovered that there are a few little gotchas in .NET 3.0’s XAML serializer that I, somehow, never ran into before.
    Read more...

    Writing a custom Main() method for WPF applications

    Creating a new WPF project in Visual Studio gives you the following pretty simple application markup and code: <Application x:Class="WpfApplication2.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="Window1.xaml"> </Application> namespace WpfApplication2 { public partial class App : Application { } } Understanding how it really works, and how to supply your own custom Main() method, is just a search query away. You basically need to change the application’s build action from “Application Definition” to “Page”, create a constructor that calls “InitializeComponent”, and write your Main() by eventually calling one of the application’s “Run” method overloads.
    Read more...

    Exposing global variables in IronPython

    Lately I’ve been playing around a bit with IronPython and how to embed it inside an application to add scripting features. I’m still figuring things out, but I had a hard time exposing global variables to the Python environment.

    The idea was to expose a couple of .NET objects (mainly a few important managers/singletons from the app’s API) as global variables so that scripts could access and act on the important parts of the app (query the database, batch run actions, etc.).

    At first, I exposed some objects as variables of my ScriptScope:

    public void SetupScope(ScriptScope scope)
    {
        scope.SetVariable("test_string", "This is a test string");
        scope.SetVariable("test_callback_method", new Action(TestCallbackMethod));
        scope.SetVariable("test_callback_function", new Func<string, string>(TestCallbackFunction));
    }

    The problem was that only interactive scripting would get access to those variables (I had a simple UI for typing commands to be executed on that ScriptScope). Using “test_string” in a function loaded from a module would result in a “name ‘test_string’ is not defined” error. Using either “import” or “global” would not fix it.

    Read more...

    Conditional operator fun

    A good friend of mine sent me this little “gotcha” a few days ago, so I thought I’d share: #include <iostream> #include <string> void main() { int a = 0; int* ptrA = &a; const int b = 1 ; <span style="color: blue">const int</span>&amp; refA1 = (ptrA ? *ptrA : 1); <span style="color: blue">const int</span>&amp; refA2 = (ptrA ? *ptrA : b); std::cout &lt;&lt; refA1 &lt;&lt; std::endl; std::cout &lt;&lt; refA2 &lt;&lt; std::endl; a = 42; std::cout &lt;&lt; refA1 &lt;&lt; std::endl; std::cout &lt;&lt; refA2 &lt;&lt; std::endl; }
    Read more...

    IronCow and the design for testability

    IronCow is a library that wraps the Remember The Milk (RTM) web services. The “upper layer” of the IronCow API is an object model that stays in sync with the server and is designed with data binding in mind. Of course, one of the things that went into IronCow’s design was testability. IronCow ships with a suite of unit tests that, well, test that the API is working fine. However, there’s another testability aspect: how the clients of your API are going to test their stuff.
    Read more...

    A variation on the auto-completing WPF TextBox

    In this world of web 2.0 tagging madness, any good (or at least shiny enough) application needs a way to apply tags in a user-friendly way, namely with auto-completing text boxes. For example, the awesome Remember The Milk application has this: What if we want a similar text box in WPF that would display a drop-down list of all the existing tags that match what the user is currently typing? The answer is, unfortunately, that we need to do it ourselves… but don’t be afraid, we’ll be playing around with cool things!
    Read more...

    WPF application patterns continued: convention over configuration

    In my previous post on WPF application patterns, I went over a few of the most common patterns available, and gave some pointers on how to implement them in WPF. I mentioned how you could use a dependency injection framework to decouple the implementation of your views and controllers from each other. However, the problem when using dependency injection out of the box is that you need an interface to bind to.
    Read more...

    Announcing IronCow

    One of the projects I'm working on at home, IronCow, is now in a state of "somewhat usable alpha". It's a .NET API that allows developers to use Remember The Milk, the to-do list website, from any .NET language. IronCow is composed of two layers. One layer is a "dumb" wrapper around the public REST API, in way very similar to what FlickrNet does with Flickr's own REST API. The second layer is a "rich" object model that exposes your tasks (and other data) through classes that stay in sync with the server as you manipulate them.
    Read more...

    WPF application patterns

    There's quite a few articles about using the MVC, MVP, MVVM and other MSomethingSomething patterns with WPF applications out there, but I think there's still quite a few things to say on the subject before we can implement all those wonderful acronyms from A to Z without too much worry. The goal of each of those patterns is to achieve separation of concerns for code reuse, scalability, extensibility, and testability, along with that warm fuzzy feeling you get when you look at your code and you think "wow, this is nice".
    Read more...

    Almost everything you need to know about XAML serialization (part 2)

    In part one of this little simple series, we saw how to use XAML as a file format for our own custom types. However, we wanted to reduce the verbosity of XML for specifying objects with only a few properties. This can be done with MarkupExtensions. We saw that the XAML serializer is asking if our types can be converted to the MarkupExtension class. Let's give our CustomizableEngine class the ability to do that:
    Read more...

    Custom provider attributes in a configuration element (part 2)

    In the first part of this little series, we implemented a simple, read-only way to get custom attributes from a configuration element, using a provider pattern use case. We ended trying to modify the configuration file, without much success. Right now, we have the following method, called at the end of the program: private static void SimulateConfigurationChange() { var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); var section = configuration.GetSection("cookieFactory") as CookieFactoryConfigurationSection; section.CookieProvider.Options["maxCookies"] = "6"; configuration.
    Read more...

    Custom provider attributes in a configuration element (part 1)

    A common pattern in .NET is the "provider pattern", where you have an abstraction for pulling data out of something (a database, a file, your ass, etc.), and one or several implementations of this interface (usually, one for each "something" you can pull data out of). For this example, we're going to get cookies (the biscuit, not the browser token, you sad nerd) from some "cookie provider". public class Cookie { public string Flavor { get; set; } } public interface ICookieProvider { Cookie ProvideCookie(); } class Program { static void Main(string[] args) { ICookieProvider provider = GetCookieProvider(); Cookie cookie = provider.
    Read more...