Archive

Archive for the ‘Uncategorized’ Category

Revisiting recursion with Dynamic Methods

January 8, 2010 Leave a comment

Dynamic methods were added to .NET back in the 2.0 release as part of Lightweight Code Generation, and lots of technologies (i.e. IronPython) use them to do their dynamic dirty work of emitting code at runtime. Dynamic methods are methods that you create at runtime through System.Reflection.Emit much like you would generate an assembly with reflection, only you don’t need to put the method in an assembly, so there isn’t an assembly hanging around in memory…GC can clean up the JIT’d code after the method goes out of scope.

The code is also a lot more concise: no AssemblyBuilder, ModuleBuilder, TypeBuilder, MethodBuilder needed before you can write a dynamic method. For an example, I’m revisiting my old recursive Fibonacci function to illustrate writing a dynamic method and also show the performance cost for the runtime to resolve dynamic methods. Recursive functions demonstrate this the best because each recursion requires dynamic method resolution to occur.

DynamicMethod dm = new DynamicMethod("Fib", typeof(int), new Type[] { typeof(int) }, true);
ILGenerator il = dm.GetILGenerator();
Label isEqZero = il.DefineLabel();
Label isNotEqZero = il.DefineLabel();
Label isNotEqOne = il.DefineLabel();
Label retLabel = il.DefineLabel();
LocalBuilder local = il.DeclareLocal(typeof(int));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ceq);
 
il.Emit(OpCodes.Brfalse, isNotEqZero);
// If it got here, then the input was zero, so go to return label.
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Br, retLabel);
 
il.MarkLabel(isNotEqZero);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Ceq);
il.Emit(OpCodes.Brfalse, isNotEqOne);
// If it got here, then the input was one, so go to return label.
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Br, retLabel);
 
il.MarkLabel(isNotEqOne);
// Should do recursion here.
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Call, dm);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldc_I4_2);
il.Emit(OpCodes.Sub);
il.Emit(OpCodes.Call, dm);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Add);
il.Emit(OpCodes.Stloc_0);
 
// Loads the first local variable onto the stack and returns it.
il.MarkLabel(retLabel);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);
 
Func<int, int> invokeDynamicMethod = (Func<int, int>)dm.CreateDelegate(typeof(Func<int, int>));
for (int i = 0; i <= 40; i++)
{
    int result = invokeDynamicMethod.Invoke(i);
    Console.WriteLine("{0} {1}", i, result);
}

If you run this, you’ll notice that it gets slower with larger numbers because bigger numbers require more invocations of the dynamic method. Of course, you could solve this problem without using recursion, but I wanted to illustrate the performance penalty. That said, Lightweight Code Generation and dynamic methods give you some great flexibility without the additional baggage of generating a full fledged .NET assembly.

Terrible UX people are creating in Silverlight just because they can

December 9, 2009 1 comment

After reading some really ridiculous posts of people doing stuff with Silverlight that you really shouldn’t do, I thought I’d make a post of my own, showing how you can display progress bars inside drop down lists that are nodes on a treeview that auto-expand on mouseover just like I tweeted about. I think doing this is a terrible idea, but since every other day I see a blog posting on how to do something in Silverlight that makes for a very bad user experience, I thought I would contribute an example of my own. I hope you enjoy.

I wish I could upload my Silverlight control to WordPress so you could see it running live. Maybe I’ll find someplace else to host it. In the meantime, you can probably imagine how atrocious this looks, but maybe you’re also amazed by how easy it is and how clean the markup can be when making something that looks and behaves so terribly.

Too add to the fun, the source code in this blog post is spilling over the margins.

<usercontrol xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls" x:class="TerribleUX.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:ignorable="d" d:designheight="300" d:designwidth="400">
    <usercontrol.resources>
        <style targettype="ProgressBar" x:key="pbStyle">
            <Setter Property="Minimum" Value="0" ></Setter>
            <Setter Property="Maximum" Value="100" ></Setter>
            <Setter Property="Height" Value="30" ></Setter>
            <Setter Property="Width" Value="125" ></Setter>
            <Setter Property="Minimum" Value="0" ></Setter>
        </style>
        <style targettype="ComboBox" x:key="cbStyle">
            <Setter Property="Height" Value="30" ></Setter>
            <Setter Property="Width" Value="130" ></Setter>
        </style>
        <datatemplate x:key="tvDataTemplate">
            <combobox mouseenter="ComboBox_MouseEnter" style="{StaticResource cbStyle}">
                <comboboxitem>
                    <progressbar value="25" style="{StaticResource pbStyle}"></progressbar>
                </comboboxitem>
                <comboboxitem>
                    <progressbar value="65" style="{StaticResource pbStyle}"></progressbar>
                </comboboxitem>
                <comboboxitem>
                    <progressbar value="35" style="{StaticResource pbStyle}"></progressbar>
                </comboboxitem>
            </combobox>
        </datatemplate>
    </usercontrol.resources>
    <grid x:name="LayoutRoot" background="White">
        <toolkit:treeview>
            <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                    <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                    <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                </toolkit:treeviewitem>
            </toolkit:treeviewitem>
            <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
            </toolkit:treeviewitem>
            <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
                <toolkit:treeviewitem mouseenter="TreeViewItem_MouseEnter" headertemplate="{StaticResource tvDataTemplate}">
            </toolkit:treeviewitem>
        </toolkit:treeviewitem></toolkit:treeviewitem></toolkit:treeviewitem></toolkit:treeviewitem></toolkit:treeviewitem></toolkit:treeviewitem></toolkit:treeviewitem></toolkit:treeviewitem></toolkit:treeview>
    </grid>
</usercontrol>

And here are the event handlers:

private void ComboBox_MouseEnter(object sender, MouseEventArgs e)
{
    ComboBox cb = sender as ComboBox;
    if(cb != null)
        cb.IsDropDownOpen = true;
}

private void TreeViewItem_MouseEnter(object sender, MouseEventArgs e)
{
    TreeViewItem tvi = sender as TreeViewItem;
    if (tvi != null)
        tvi.IsExpanded = true;
}
Categories: Uncategorized

Comparing Clouds: EC2, Azure, App Engine

November 25, 2009 4 comments

There are a few definitions of cloud computing out there, but now that three big players (Amazon, Google, and Microsoft) are solidifying on what they offer (and what it costs), there seems to be a pretty consistent purpose for cloud computing: the ability to increase infrastructure capacity on the fly. In some ways, this is similar to keeping servers in a hosting facility – the hosting company handles some level of IT administration, ensures the power and network connectivity are available, etc. The difference in cloud computing is that getting more servers at a hosting facility takes time…typically days or weeks. In cloud computing, you can increase capacity immediately, and also reduce it. This provides huge advantages for systems that have usage spikes periodically, as you can increase and reduce infrastructure when needed, rather than paying for the unused capacity of beefy servers (and electricity and IT staff) that sit idle most of the time. You pay for what you use in terms of storage, processing and memory capacity, and internet data transfer.

From that standpoint, Amazon’s Elastic Compute Cloud (EC2), Google’s App Engine, and Microsoft’s Azure are very similar. They all provide administrative consoles to manage your infrastructure’s capacity within their hosting facility on the fly. You pay only for the amount of infrastructure you use, rather than paying for oversized infrastructure to meet peak demands. There are quite a few differences in their administrative consoles, security capabilities, and of course, pricing. But the biggest differences are in the type of infrastructure they offer. I’ve been evaluating the different cloud platforms for some time, and now that Microsoft has official pricing and Go Live dates, I thought others might find my research helpful in understanding and choosing a platform.

Amazon’s EC2 essentially provides you with hosting for virtual machines (called Amazon Machine Images). They have various images of Windows, Linux, and Unix operating systems, with various database and application server software packages available. You also have the ability to create your own virtual machine images which whatever software you will need. You also get to customize the type of hardware available for running your image – standard, high-memory, and high-processing. For prepackaged images with software bundled in, you typically pay a little extra per processing hour, covering things like licensing costs. Links to pricing, listings of prepackaged instances, and other details about EC2 are available at the end of this post.

Microsoft’s Windows Azure is similar to EC2 in some respects, as the amount you pay depends entirely on the number of instances you’re running. The difference is that you can’t configure any image you want. Everything you do needs to run on Windows Azure’s Platform, which supports a wide variety of languages and runtimes, but not everything. You’re limited to Azure SDK’s for .NET, PHP, Ruby, Python, or Java. As for database support, you have SQL Azure, which was recently announced to have full T-SQL compatibility with Microsoft’s SQL Server. You also can choose to use a mySQL database on the Azure platform. This is fairly broad application support, especially for Microsoft, and if you can live within these constraints, there are two big advantages. Administration of instances is much simpler – you only need to administer your application, rather than administering the whole operating system. Microsoft handles all the OS administration and updates, which means you only need to worry with your application administration. The other advantage is simplified pricing, which is due primarily to the limited application offerings. You just pick what level of hardware you want for each Windows Azure instance, and what size database you’ll want for SQL Azure (currently only supporting up to 10GB databases). Links to pricing, SDK resources, and other details about Azure are available at the end of this post.

Google’s App Engine (GAE) gets rid of the whole concept of an instance. You don’t have to predetermine or preconfigure the number of instances you’ll need to service your application. App Engine will let it use however many requests, bandwidth, processing time, and storage your application happens to need. This is a nice model, as it takes out the complexities of determining how busy your site will be at any time, and spinning up more instances appropriately. You just pay for exactly what your application uses in terms of resources. Since there is no hard number of instances to help throttle your usage, to keep costs from running out of control, GAE simply provides you with quotas that you administer. The great advantage in Google App Engine is that there is a free level of quotas that lowers the barrier to entry significantly. If your application doesn’t exceed a certain level of usage, Google is essentially hosting it for free. This convenience comes with a cost, however. The Google App Engine SDK only comes in two flavors – Java and Python, and they are both sandboxed to control what you can do. For example, everything is basically request based – you can’t really have a service running in the background (although there is a Cron service that allows you to schedule jobs). You’re also limited in their SDK to using Google Accounts (although some people have workarounds for this as well). Links to pricing, SDK resources, and other details about the Google App Engine are available below.

Amazon EC2
http://aws.amazon.com/ec2/
Complete flexibility – many operating system and application options, and the ability to package your own images with whatever custom software you need.

Windows Azure
http://www.microsoft.com/windowsazure/
Simpler administration and pricing – only administer your application and the number of instances to run, rather than administering the entire virtual machine. Limited to SDK’s for .NET, PHP, Ruby, Python, and Java, with databases in SQL Azure or mySQL.

Google’s App Engine
http://code.google.com/appengine/
Even simpler administration – just administer your resource quotas. Limited to SDK’s for Python and Java, and using Google’s Datastore. Also supports a free model, with lower quotas, excellent for hosting a startup application.

So how do you choose or should you even bother with this “cloud” stuff?
It depends entirely on what you are doing. In some scenarios, hosting in the cloud just doesn’t make financial sense. If you have a basic PHP site with mySQL, you could certainly host that in Azure or EC2, but unless you have the level of high volume traffic that necessitates some dedicated servers, it’s going to cost significantly more than a run of the mill hosting plan which can offer a similar Service Level Agreement for availability and performance. If your traffic is very steady, then the ability to add and remove infrastructure on the fly isn’t as attractive, and a standard hosting center may still work well and be cost effective for you. If you’re willing and able to develop or port your existing application to run within Google App Engine or Microsoft Azure SDK’s, those probably make a lot of sense, because of the simplified administration. If you can’t work with those constraints, the Amazon EC2 cloud is a very flexible option, although you get stuck with the administration of the operating system. If you are trying to co-locate your application between your existing infrastructure and a cloud infrastructure in order to handle peak conditions or provide load balancing, Amazon EC2 and Microsoft Azure provide the capability to host applications both “on premise” (on your infrastructure) and in their cloud.

What’s the next step?
Assuming you have an application running already, you need to analyze the traffic. Is it always steady, does your application often encounter traffic spikes, are these spikes periodic or sporatic? If you frequently have large spikes, moving to a cloud environment certainly makes more sense than paying for server resources that go unused between spikes.

Which cloud?
Now you just need to choose your cloud, and that depends on the trade off between flexibility and administration. The flexibility provided by Amazon’s EC2 means you need to have some IT resources that can administer the operating system instances, but it also generally means you’ll be able to host your existing application with little to no code changes. Microsoft’s Azure and Google’s App Engine are more constrained in terms of technology choices. An existing application will require at least some code modification to run in their cloud platforms, and you’ll really need to review the application’s full architecture to determine the effort to migrate. However, there is much less IT administration, which means that once you’ve migrated, your resources can be spent on building new functionality. If you can fit in the relatively narrow bounds of the Google App Engine, there is hardly an infrastructure to manage at all. Of course, if you’re a .NET development shop, the Microsoft Azure cloud probably makes the most sense because while you could deploy to Amazon EC2, you’ll be wasting resources on server administration overhead instead of building new product features. If you’re hooking into lots of Google services, like XMPP and Maps and the Google Web Toolkit, Google App Engine is going to fit in well.

What if you’re afraid to commit?
Cloud computing is a great concept, but it is new. And there have been some highly publicized outages that can make just about everyone nervous. Many people also worry about data security, although it isn’t much different than the security afforded by a reputable hosting center. If you don’t want to commit, but would like to supplement existing infrastructure, Amazon EC2 and Microsoft Azure make the most sense. Amazon is nothing more than virtual machines that happen to reside on Amazon’s infrastructure. You can keep some infrastructure “on premise” and other infrastructure in Amazon’s virtual machines. Similarly, Microsoft’s Windows Azure has AppFabric, which is an abstraction layer that your application code writes to, allowing the same code to run in Microsoft’s cloud as in an “on premise cloud” that runs on your own infrastructure. Google’s App Engine can only run locally in somewhat of a “restricted” mode, where some of the services are not available.

There are some big players offering a lot of choices, and probably more to come in the future as the technology matures, but cloud computing is certainly one of the larger computing paradigm shifts in this decade, IMHO second only to the explosion of mobile computing.

Powershell to find the next available port

March 30, 2009 Leave a comment

Every now and then I’m installing service application on a development machine, and I just want to find the next available port that I can use. Here is a handy Powershell script to do that, which can be easily run as part of a deployment script.

param([int]$port = $(throw("Port required.")))
$isInUse = $FALSE
while(!$isInUse)
{
	trap [System.Net.Sockets.SocketException]
	{
		write-host "Unable to open socket on port $port."
		$script:port = $script:port + 1
		$script:isInUse = $TRUE;
		continue;
	}

	$listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Any, $port)
	$listener.Start()
	write-host "Socket opened successfully on port $port."
	$listener.Stop()
	$isInUse = $FALSE
	break
}
return $port

The easiest way to call this is to include it directly in another powershell script, but if you want to save this as a script that you can call from a different script as a cmdlet, you need to execute this command first, which allows execution of unsigned scripts from the local machine.

set-ExecutionPolicy RemoteSigned

After you’re done with your processing, you may want to set this back to the default restricted setting:

set-ExecutionPolicy Restricted

Giving Glade a fair shake

October 14, 2008 Leave a comment

As soon as I mentioned XAML and XUL, somebody pointed out to me that Gnome on Linux also allows you to define your user interface declaratively using XML with Glade. The v3 release of Glade uses XML to define the properties and layout of GTK widgets in a way very similar to WPF and XAML. Since XAML is only supported on Windows right now and Mono is probably a long way from any WPF support, I thought I’d give Glade a try. If it works well enough, loose XAML pages could be just an XSL transform away from Glade XML for creating GTK apps.

Since Ubuntu is the “Red Hat of the future” for bringing Linux to the mainstream desktop, I decided to do this on Ubuntu and found that getting a usable application together is pretty simple. To avoid trashing an existing PC, I installed Sun’s VirtualBox to create an Ubuntu installation there.

Once Ubuntu is up, go to Applications | Add/Remove Programs, and search for “Glade”. Add “Glade Interface Designer” (if you see more than 1, choose the more popular one just like you’re building the perfect kickball team). At this point, you can go through this tutorial to learn the basics of Glade.

Once you have a basic UI defined in Glade’s XML, this is fairly analogous to your XAML file in WPF, and you’ll need to write some code to load up the application and handle UI events (signals). This is all defined in the tutorial, but what the tutorial doesn’t cover is how to set up your development environment, so I’ll go through that here.

Ubuntu doesn’t come with all the development tools or GTK header files installed, so you need to download those. For C/C++, you need to execute apt-get at a terminal to download and install the development tools you’ll need:

sudo apt-get install build-essential
sudo apt-get install libgtk2.0-dev
sudo apt-get install libgtk2.0-doc
sudo apt-get install libglib2.0-doc

If you go through all the forums, you’ll find that everybody wants you to use GEdit and make for writing your code. I tried that first, and aside from the fact that you have to do command line debugging, it works pretty well. But if you like an IDE with an integrated debugger, Eclipse is the best (and still open source so hopefully I don’t get attacked for recommending it). However, Eclipse will flip out if you don’t configure it correctly, so follow these steps.

You can get Eclipse using the same Add/Remove Programs in Ubuntu, but you need to switch “Show:” to “All Open Source applications” or “All available applications” and search for “eclipse”.

Once Eclipse is installed, you need to get the tools for C/C++ development, run it, and from the Help menu, choose “Software Updates” –> “Find and Install…” Select “Search for new features to install”, click “Next”, check “Callisto Discovery Site”, click “Finish”, choose the nearest mirror site. When you get back the “Search Results” screen, expand “Callisto Discovery Site” and check “C and C++ Development Tools.” Click Next to continue through the installation process. When prompted, go ahead and restart Eclipse.

When Ecplise starts back up, go to the File menu, click New | New Project, and then expand the C or C++ node to get to a Managed Make C or C++ project (whichever you want). Once you get the project up, you can create a “main.c” for creating the code per the Glade and GTK+ tutorial I mentioned above. When it starts complaining about not being able to find gtk.h, whatever you do, don’t start trying to add Includes and Link Libraries . This is not the Linux way. Instead, right click on your new project and go to Properties, then go to the settings for C/C++ Build.

Under the GCC C Compiler (or GCC C++ Compiler if you’re build .cpp files), go to Miscellaneous. At the end of the “Other flags” text box, add the following, which will execute pkg-config to get the correct includes for your system:

`pkg-config --cflags gtk+-2.0`

Also, under the GCC C++ Linker, Miscellaneous, “Other flags”, add the following, which will get the correct libraries and tell the linker to export any signal handlers you add to widgets in Glade:

`pkg-config --libs gtk+-2.0 gmodule-export-2.0`

Now you should be able to build and run your code directly from Eclipse. If you get warnings on the Eclipse console about “Could not find signal handler”, either you are missing the “gmodule-export-2.0″ or your method signature for your signal handler doesn’t match what is specified in the XML file created by Glade Interface Designer.

One last thing – in the Glade and GTK+ tutorial, they use gtk-builder-convert to convert the file from libglade format to GtkBuilder format. It makes sense to do this in a pre-build step, which you can also do from the project properties. Under C/C++ Build, click the Build Steps tab, and under the Pre-build step Command, enter something like this:

gtk-builder-convert ~/workspace/MyGladeProject/GladeUI.glade ~/workspace/MyGladeProject/GladeUI.xml 

That way any changes you make in Glade Interface Designer will make it over into the file you’re loading in your GtkBuilder calls. It would be nice if there were an Eclipse plugin for Glade Interface Designer that would load the application within Eclipse and provide a fully integrated environment, but until that happens, the Pre-Build step saves a lot of headache.

All this took me about a day to figure out, mostly spent messing with different Ecplise options before I decided to stop trying to configure the Includes and Libraries and just use Miscellaneous to make the call to pkg-config. Hopefully this saves someone else a lot of time.

As far as my XAML to Glade/GTK+ XML comparison, they are actually very comparable for the most part, but the one major thing missing from GTK+ in general is declarative data binding. You still end up writing a lot of code just to get and set data in your UI. This guy seems to agree, and there is a Gtk-Databind project for GTK#, but unfortunately it doesn’t seem to be getting much attention by the core GTK development group.

XAML and Code Separation

October 7, 2008 3 comments

XAML allows you to create a user interface to display and interact with data declaratively, with little or no code. Microsoft obviously wants you to create a code behind file for every XAML window or control you build, but if you can avoid that, you’ll gain some terrific flexibility in your application. XAML becomes nothing more than your presentation layer – a complete user interface definition in XML – no business logic or data access code intertwined with your UI. If your user interface is just a string of XML, you have a lot more options for deploying, maintaining, and extending that user interface beyond just compiling it into your application. Store it in a file system, store it in a database, generate it dynamically at runtime with XSL…

XML based UI technologies have come a long way over the years with technologies like XUL which powers Mozilla applications and MXML for Macromedia’s Flex. The real strength of XAML is in data binding and its tight integration with the .NET CLR, which is generally the platform of choice for business applications. With data binding, your UI elements are truly observing your underlying data which means when the data changes, the controls update automatically without any extra code. Of course, extensibility is one of the most important features of any API, and with XAML and WPF there are many options for extensibility that are in easy reach of any developer familiar with .NET.

To build the WPF extensions necessary for a loose XAML application, you will probably need to become familiar with a few things that aren’t in a traditional Windows or Web application developer’s toolkit.

  1. Reflection
  2. Application tracing
  3. Command interface (System.Windows.Input.ICommand)

Reflection will allow you to make components that are highly configurable, which means they are very reusable in many different scenarios. You can adjust the configuration at runtime using CLR properties and WPF dependency properties. Just about everything in XAML uses reflection to some degree, so becoming familiar with the technology is very helpful.

Probably the most frustrating thing about declarative data binding is there is no source code so you can’t easily debug your application to find out why something isn’t binding or updating. However, .NET has plenty of built in tracing features that will help to explain why things aren’t working as expected.

One of the first problems that occur when trying to use loose XAML is that event handlers can only exist in a code-behind class, which you won’t have in a XAML only scenario. With WPF, Microsoft added the System.Windows.Input.ICommand interface, which is a way to receive input from your application without event handlers. ICommand has two methods, CanExecute(object):bool and Execute(object):void, and you can use command binding on buttons, hyperlinks, and menu items to send data to any ICommand implementation in the form of a CommandParameter.

Once you’ve mastered these three technologies, you’ll likely never want or need code-behind again, and you can achieve complete seperation of presentation and application logic. Then it is on to the real extensibility of WPF, with Dependency Properties, Attached Properties, and Markup Extensions. Dependency Properties allow you to create special properties on your own classes that support data binding. Attached Properties allow you to create special properties on a static class that you can “attach” to any Dependency Object, which means you don’t always have to extend a class just to give it more properties. And in a pinch, when you find there is a little feature missing in WPF, like getting the index of an item in a WPF ItemTemplate, you can use a Markup Extension, which will be replaced by the XAML parser with whatever data is returned by its ProvideValue method at runtime.

Categories: Uncategorized
Follow

Get every new post delivered to your Inbox.