I recently started working heavily with KnockoutJS and I gotta say it’s one of the coolest things I’ve ever used. As an ASP.NET MVC developer, I rely quite a bit on the ability to set a layout page (or two) and have a master page/content page relationship in my sites. I encountered however that Knockout seems to flake out a little but when you have <script> sections scattered in your content pages. The one I have in the layout page works fine, but the ones I define in the content pages did not. The content of these script tags is obviously my view models and can be defined either inline or linking to a js file. Either way, no workie. When viewing the page source on the rendered page, you can see the <script> section defined in the layout page up on top and the one for the content page down in the middle somewhere. For testing purposes, I moved the content page’s <script> content to the layout page and guess what, it all works fine. Obviously in the case of having more than one ViewModel, you have to use the applyBindings method with the “root element” argument. So after a little searching and finding nothing on this problem (I guess Knockout being so new, searches still lack quite a bit – yes, even StackOverflow), something occurred to me and it fixed my problem: I can declare the content page’s <script> section inside a @section sectionname { }. Then in my layout page I used the @RenderSection command to render that section using the name I gave it. Now the scripts can be physically encapsulated within the content page to which they belong, but render up at the top of the layout page’s <script> section – best of both worlds. I hope this posting reaches the search engines and helps others who may have run into this. Until next time…
I’m running two events in the northeast called MVVM DevReady coming up this month. The first one is in Philly (Malvern actually) and will run on Saturday the 19th of March. The second is the following Monday, the 21st, in the NYC Microsoft office. Both events are FREE of charge but registration is limited and is quickly filling up. We just put up the registration site yesterday and are more than half full already. I will be giving the first three sessions, with the local DE giving the fourth, and our sponsor providing the last session of the day. These events could not have been possible if not for our sponsor, Developer Express. They are not only covering event expenses but are flying out one of their chief evangelists, Seth Juarez, to present the session personally. The registration sites are: 3/19/2011 - Philly: http://devready-estw.eventbrite.com/ 3/21/2011 - NYC: http://devreadynyc.eventbrite.com/ Get your development skills ready for MVVM (Model View View Model Design Pattern) and build some exciting applications for WPF, Silverlight or Windows Phone. In this all day event you will learn everything you need to know to get start with MVVM. We will start with the basics and end with some more advance topics.
I’ve been beating my head against the wall with a small problem and after lots of trial and error, and some searching around, I found the answer – and it was NOT obvious ! The problem space was simple and common: I have placed a lot of my styles, data templates, and converters into separate XAML files (ResourceDictionaries), with the idea of just declaring them in the App.Xaml since I’m pretty much using these all over the application. I started out declaring things in my App.Xaml like this: <Application.Resources>
<controls:BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" />
<refractionConverter:ReverseBooleanToVisibilityConverter x:Key="reverseBooleanToVisibilityConverter" />
<refractionConverter:PercentageConverter x:Key="percentageConverter" />
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
</ResourceDictionary>
<ResourceDictionary Source="Resources/SharedResources.xaml" />
<ResourceDictionary Source="Resources/MdiTemplates.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Looks simple enough right? Wrong.
The second I moved the converters from the individual User Controls to the App.Xaml, styles that are declared in the SharedResources.xaml file became unreachable. In my debugging efforts, I tapped into the Application_Startup event to examine the resources that WPF was loading. I noticed that the value of this.Resources.Count was 4, but the value of this.Resources.MergedDictionaries.Count was 0.
So I continued digging and here’s what I found out:
Once you commit to using MergedDictionaries in your App.Xaml, you must use them for everything. I moved the three converters inside the MergedDictionaries section and tested the debugging again. This time, this.Resources.Count was set to 0, and this.Resources.MergedDictionaries.Count was set to 3. This told me the resources I listed as MergedDictionaries were now loading. The key indicator that things were better is that my styles now worked.
Here’s the code:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<controls:BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter" />
<refractionConverter:ReverseBooleanToVisibilityConverter x:Key="reverseBooleanToVisibilityConverter" />
<refractionConverter:PercentageConverter x:Key="percentageConverter" />
</ResourceDictionary>
<ResourceDictionary Source="Resources/SharedResources.xaml" />
<ResourceDictionary Source="Resources/MdiTemplates.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
I hope this helps since believe it or not, though there’s a lot of code samples out there, much of it is unclear and flat out wrong.
Until next time…
One of my latest challenges involved the topic of WPF sizing. I’m referring to the manipulation of control widths in relation to their parent widths. Most books tell you that this happens automatically, but I’m here to say otherwise gentle reader. Now, I am fully prepared to admit that I may have missed something so if you’re a WPF expert out there and you think there is a better way to do what I’m going to show you, please respond. So here is my situation: I have a window (user control actually, but then almost everything is in most WPF applications). My window defines a grid with two columns, each which will contain a user control of their own. It looked something like this: <Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<src:Control1 Grid.Column="0" x:Name="ctlControl1" DataContext="{Binding Path=Control1ViewModel}" />
<src:Control2 Grid.Column="2" x:Name="ctlControl2" />
</Grid>
The user control called Control1 contains a ListView control which defined an ItemTemplate to construct the content structure of each item. The effect I wanted was to show the data for each item in read-only mode and provide an “edit” icon on each item. Pressing it would convert that item to editable textboxes. I got that working fine by providing two Grids inside my data template, setting one of them invisible, then using commanding on the button icons to change the view-model state to switch the Visibility of each grid was bound – worked like a charm and is a really nice effect.
My problem was that both the TextBlock and TextBox controls in each item view sized to its contents, then the widest one became the width of the actual ListView that contained everything. Originally, the column that contained this entire user control (defined above) was set to Auto, so of course it would widen to the width of the longest text control. This totally sucked.
I added a splitter to the grid in the user control that contained the other two controls and the results at first were weird. I took the recommendation of most books and added the GridSplitter to its own column (set to Auto width) at first. This enabled me to resize the grid columns but by then, the content user control’s width was already set and it would not resize along with my resize-drag. Dragging the splitter to the right, left the contents of the first column fixed, and dragging to the left basically didn’t work past the already fixed-width of the first column. I fixed this by adding the GridSplitter as the last control on the same column as one of the controls, like this:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<src:Control1Grid.Column="0" x:Name="ctlControl1" DataContext="{Binding Path=Control1ViewModel}" />
<GridSplitter ResizeDirection="Columns" Grid.Column="0" Width="3" />
<src:Control2 Grid.Column="2" x:Name="ctlControl2" />
</Grid>
Now when I drag the splitter, the columns follow along the resize in both directions; however the TextBlock and TextBox controls in my ListView remain sized to their contents and would not stretch in either direction. This still totally sucked.
After playing around significantly with this, I discovered that the ListView itself was sizing and resizing dynamically as I dragged my splitter so I needed to get the contents of each item to size similarly. The solution was to bind the Width of each of my TextBlock and TextBox items to the width of the ListView in which they were contained. I gave the ListView control a name (I don’t normally name my controls since most of my work happens in the View-Model anyway), then set the Width property of the contained controls like this:
<ListView Name="lvw1" ItemsSource="{Binding}" DataContext="{Binding Path=VuewModelPropertyGoesHere}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid Visibility="{Binding Path=EditMode, Converter={StaticResource notEditModeVisibilityConverter}, Mode=OneWay}">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="Auto" />
<RowDefinition Height="25" />
<RowDefinition Height="10" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Path=Name}" TextWrapping="Wrap" HorizontalAlignment="Stretch" Width="{Binding ElementName=lvw1, Path=ActualWidth}" Margin="0,0,5,0" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Path=Description}" TextWrapping="Wrap" HorizontalAlignment="Stretch" Width="{Binding ElementName=lvw1, Path=ActualWidth}" Margin="0,0,5,0" />
.
.
.
</Grid>
<Grid Visibility="{Binding Path=EditMode, Converter={StaticResource editModeVisibilityConverter}, Mode=OneWay}">
<Grid.RowDefinitions>
<RowDefinition Height="25" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="10" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Row="0" Grid.Column="0" Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ElementName=lvw1, Path=ActualWidth, Mode=OneWay}" Margin="0,0,5,0" VerticalAlignment="Center" />
<TextBox Grid.Row="1" Grid.Column="0" Text="{Binding Path=Description, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" AcceptsReturn="True" MaxLines="3" MinLines="3" VerticalScrollBarVisibility="Auto" Width="{Binding ElementName=lvw1, Path=ActualWidth, Mode=OneWay}" Margin="0,0,5,0" VerticalAlignment="Center" />
This totally fixed my problem… almost. While the binding worked perfectly, the look I got left one little detail to be desired. You see, now the width of the textboxes as equal to the width of the ListView. This made their right edge disappear, and no margin and padding setting would fix it.
What I needed to do is set the width of the controls to slightly less than the width of the ListView; 10 pixels less to be exact. Apparently in WPF, you either bind or you do not bind; not a combination of the two. And you certainly cannot do mathematics in the XAML. So what to do?
At this point, I had become quite comfortable with the idea of a type-converter so this is the first thing that sprung into my mind. I created a type converter that I could use in this binding. The job of the type converter would be to take the incoming width, and rather than convert it to another type, simply adjust by a certain amount and return that number. And what amount you ask? Well, the type converter gives you a “parameter’ argument than you can fill in the XAML, so the answer is: any amount I desire.
The end-result worked and looked great. Here’s the type converter code:
public class WidthToParentConverter : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
double width = (double)value;
double adjustment = Convert.ToDouble(parameter);
return width + adjustment;
}
object IValueConverter.ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
double width = (double)value;
double adjustment = Convert.ToDouble(parameter);
return width - adjustment;
}
}
And here’s the adjusted XAML for the textboxes:
<TextBox Grid.Row="0" Grid.Column="0" Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" Width="{Binding ElementName=lvw1, Path=ActualWidth, Converter={StaticResource widthToParentConverter}, ConverterParameter=-10, Mode=OneWay}" Margin="0,0,5,0" VerticalAlignment="Center" />
<TextBox Grid.Row="1" Grid.Column="0" Text="{Binding Path=Description, UpdateSourceTrigger=PropertyChanged}" TextWrapping="Wrap" AcceptsReturn="True" MaxLines="3" MinLines="3" VerticalScrollBarVisibility="Auto" Width="{Binding ElementName=lvw1, Path=ActualWidth, Converter={StaticResource widthToParentConverter}, ConverterParameter=-10, Mode=OneWay}" Margin="0,0,5,0" VerticalAlignment="Center" />
I struggled with this for a quite a bit, mainly because of inexperience, but now I know exactly what to do in this situation and I hope sharing it helps some of you as well.
Until Next Time…
Got your attention yet? Well, truth be told, it doesn’t really have multiple inheritance; not in the true sense. However, with a little creativity in technique, and provided your needs are not too deep, you can simulate a pseudo-multiple-inheritance scenario. So let’s start by totally stating the obvious. We have BaseClass1 and BaseClass2, each with methods that write out to the console a message identifying themselves. public class BaseClass1
{
public void BaseMethod1(string arg1, bool arg2)
{
Console.WriteLine(string.Format("BaseMethod1 in BaseClass1 called with arguments: {0} & {1}.", arg1, arg2.ToString()));
}
public void BaseMethod2(string arg1, string arg2)
{
Console.WriteLine(string.Format("BaseMethod2 in BaseCall1 called with arguments: {0} & {1}.", arg1, arg2));
}
}
public class BaseClass2
{
public void BaseMethod1(string arg1, bool arg2)
{
Console.WriteLine(string.Format("BaseMethod1 in BaseClass2 called with arguments: {0} & {1}.", arg1, arg2.ToString()));
}
public void BaseMethod2(string arg1, string arg2)
{
Console.WriteLine(string.Format("BaseMethod2 in BaseCall2 called with arguments: {0} & {1}.", arg1, arg2));
}
}
Now we have a couple of other classes which have their own methods and each also inherits from one of the base classes. We all know that .NET will limit the inheritance to only one class.
public class DerivedClass1 : BaseClass1
{
public void DerivedMethod1()
{
Console.WriteLine("DerivedMethod1 in DerivedClass1 called.");
}
}
public class DerivedClass2 : BaseClass2
{
public void DerivedMethod1()
{
Console.WriteLine("DerivedMethod1 in DerivedClass2 called.");
}
}
If I instantiate these two classes, I can call either their own methods or the ones declared in the base class, right?
DerivedClass1 dc1 = new DerivedClass1();
dc1.BaseMethod1("hello", true);
dc1.BaseMethod2("hello", "world");
dc1.DerivedMethod1();
DerivedClass2 dc2 = new DerivedClass2();
dc2.BaseMethod1("hello", true);
dc2.BaseMethod2("hello", "world");
dc2.DerivedMethod1();
Have I insulted your intelligences enough by stating the obvious in about as boring fashion possible? Well I did that for a reason. See, my needs are to give the functionality provided by both base classes to a derived class and still keep it apart in two separate entities; only my so-called entities won’t be classes this time, they’ll be extension methods.
Extension methods, introduced in .NET 3.5, allow me to add functionality in the for of methods to existing types. This is a little like subclassing the type, but in a different way. You can add extension methods to types that are sealed, and don’t accept subclassing. You can also add them to classes that meet a certain contract or more specifically, implement a specific interface. That’s the technique I’m gong to use now.
As you more than likely know, .NET types can only derive from a single type, but they can implement as many interfaces as you need. So the firs thing I’m going to do is refactor my base classes so they are interfaces instead. Yeah, I know, interfaces don’t offer implementation, just definition. Don’t worry I’ll get to that. What you’ll notice though is the simplicity of my two interfaces
public interface IBase1
{
}
public interface IBase2
{
}
By simplicity I mean, emptyness. These interfaces are basically just marker interfaces and will contain no definitions for anything. What they will do is offer an abstraction on which to define an extension, using extension methods. Extension methods are defined as static methods first of all. In fact, the way we code them is simply syntactic sugar for the actual static methods into which the language compiler will turn them. The first argument of each static method will correspond to the type I want to “extend”, and is identified as such with the word this in front of it.
public static class Base1Extensions
{
public static void Base1Method1(this IBase1 baseClass, string arg1, bool arg2)
{
Console.WriteLine(string.Format("BaseMethod1 from IBase1 called with arguments: {0} & {1}.", arg1, arg2.ToString()));
}
public static void Base1Method2(this IBase1 baseClass, string arg1, string arg2)
{
Console.WriteLine(string.Format("BaseMethod2 from IBase1 called with arguments: {0} & {1}.", arg1, arg2));
}
}
public static class Base2Extensions
{
public static void Base2Method1(this IBase2 baseClass, string arg1, bool arg2)
{
Console.WriteLine(string.Format("BaseMethod1 from IBase2 called with arguments: {0} & {1}.", arg1, arg2.ToString()));
}
public static void Base2Method2(this IBase2 baseClass, string arg1, string arg2)
{
Console.WriteLine(string.Format("BaseMethod2 from IBase2 called with arguments: {0} & {1}.", arg1, arg2));
}
}
Notice that in these methods, the first argument is of the type of one of the two interfaces. Extension methods don’t have to extend specific types, they can also extend classes that implement a certain interface or inherit from a certain base class. In this case, the former. Notice that the implementation for each of these four methods is identical to the implementations defined earlier in BaseClass1 and BaseClass2. All four of these methods could have been placed into one static class, since the class does nothing more than provide housing for the methods. But I chose to split them up to better mimic the original base-class scenario.
Now I can attach the functionality provided by these methods any class, simply by implementing the appropriate interface.
public class DerivedClass3 : IBase1, IBase2
{
public void DerivedMethod1()
{
Console.WriteLine("DerivedMethod1 in DerivedClass3 called.");
}
}
Now, DerivedClass3 can call any extension method designed to extend the IBase1 or IBase2 interfaces.
DerivedClass3 dc3 = new DerivedClass3();
dc3.Base1Method1("hello", true);
dc3.Base1Method2("hello", "world");
dc3.Base2Method1("hello", true);
dc3.Base2Method2("hello", "world");
dc3.DerivedMethod1();
This does have its limitations. Unlike a true base-class scenario, the code in each extension method can only access members of the type it is extending. And in this case, that type is an interface and an empty one at that. So obviously, this technique is useful only when the implementation code you want is not going to need any outside dependencies, while methods in a true base class can depend on other members of that base class. Another limitation is that extension methods can only be just that, methods. This technique would not work if you’re looking to simulate property inheritance.
So there you have it, multiple inheritance in .NET – ok maybe not, but pretty cool huh?
Until next time…
Callback functionality in WCF allows the service to call back to the client and send information or notification back. In essence, reversing the client-service roles. It’s a rather simple model with great benefits, specially if you want to keep the client notified on a long running process and display said notifications on the UI. However, it’s not a trivial matter to deal with proper thread handling when using this functionality. Most WCF callback demos will simply popup message boxes to show you when a callback has taken place, but if you need to do something more substantial that is UI-related, there’s a few other things you need to take into consideration. In the second installment of “This Week In Code”, I’ll give you a demonstration of a typical callback demo that you may run into often. Then I’ll change it to a more real-world scenario and introduce additional thread-handling details that you must undertake. I’m not going to turn this posting into a WCF callback tutorial so I’m going to assume that you know how callbacks work and how to set them up. Here’s some client code that calls a service: private void btnSimpleCall_Click(object sender, EventArgs e)
{
using (MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this)))
{
proxy.SimpleTest();
}
}
As you can see, it’s called from a button’s Click event. This will become important later.
And here’s the service operation that calls back to the client:
public bool SimpleTest()
{
Console.WriteLine("Serviced called. Performing callback.");
IMyCallback callback = OperationContext.Current.GetCallbackChannel<IMyCallback>();
if(callback != null)
{
callback.PerformCallback();
}
Console.WriteLine("Callback performed.");
return true;
}
The client that made the service call is a Windows Form and as I stated, it was a button that fired off the event. The form itself is the implementor of the callback contract, which is why the InstanceContext instance wraps this. Of course, the form needs the callback contract’s implementation because that’s what gets called when the service executes the callback operation. Here’s that implementation now.
public void PerformCallback()
{
MessageBox.Show("Callback from service on the client");
}
This simple example will work just fine because the callback is simply throwing up a message box. This mean it’s not accessing the actual form’s UI so there will not be any threading issues. Unfortunately, most examples you see on WCF callbacks do only this and as soon as the developer mimics this pattern but performs some UI update to the actual form, they run into problems. Let me alter my code example and explain why.
Ok, so this next example is supposed to make a service call from the form’s button, then the service will perform a potentially long iteration and every so many items in the loop, it will call back to the client to report progress. The client simply wants to use the value in the callback to update a progress bar o the form:
private void button1_Click(object sender, EventArgs e)
{
int max = Convert.ToInt32(txtMax.Text);
int step = Convert.ToInt16(txtStep.Text);
progressBar1.Minimum = 0;
progressBar1.Maximum = max;
MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));
int[] numbers = proxy.GetNumbers(max, step);
foreach (int number in numbers)
{
lstNumbers.Items.Add(number.ToString());
}
}
public void ReportProgress(int progress)
{
progressBar1.Value = progress;
}
So what do you think is going to happen here? Well we have a potential catch-22 with this scenario. By default the callback will me automatically be marshaled to the UI thread before it gets executed on the client. If that happens, accessing the progress bar directly from the callback operation is perfectly fine, except that the UI thread is currently in the middle of a service call, since it was initiated in the button click, so we have a deadlock scenario there.
One thing I can do is decorate the form (as the implementor of callback contract) with the CallbackBehavior attribute and tell it to not use the form’s Synchronization Context:
[CallbackBehavior(UseSynchronizationContext = false)]
public partial class Form1 : Form, IMyCallback
This means that the callback will now be executed on a background thread and not the same thread as the one that made the service call initially (which is the default behavior). But now I’ve introduced another problem. The ReportProgress callback operation can no longer directly access the UI since it’s not on the UI thread, so I need to marshal up to the UI thread in order to access the progress bar.
The best way to do this is to use the form’s Synchronization Context; a feature introduced back in .NET 2.0 but still relatively unknown. Rather than use the old “invoke” technique, I’m going to grab the form’s synchronization context as early as possible and store it in a class-wide variable. It doesn’t get any earlier than the form’s constructor, so I’ll do it there:
public Form1()
{
InitializeComponent();
_SyncContext = SynchronizationContext.Current;
}
SynchronizationContext _SyncContext = null;
Now I have accessible to me at any time, a variable that represents the form’s thread execution context; and I can use this variable from any thread I want since it will always point back to the UI thread.
Next, I’ll modify the callback operation to use the _SyncContext object in order to fire code to the thread it represents, in this case the UI thread:
public void ReportProgress(int progress)
{
SendOrPostCallback setText = delegate
{
progressBar1.Value = progress;
};
_SyncContext.Post(setText, null);
}
Well, that takes care of my marshaling task, but I’ve just introduced the old problem all over again. Remember, the UI thread was in use by the button’s event which is not over yet. It seems I’m going round and round with nowhere to go. Well, I do have a way out of this. The solution to the problem lies in the way I fired off the service operation. If you recall, my goal was to fire off the operation, receive occasional callbacks, and then once the service call was complete, I want to display results to a list box. What I need to do is not lock up the UI while I make the service call so I’m going to fire off the service call on another thread; but not just the service call, the update to the list box as well. If I don’t do both, then the service call will fire on another thread and the list box will attempt to update right away. So the button’s Click event will make the service call on a separate thread, after which, on that same thread it will update the list box with the service operation results. But since that’s a UI operation, it needs to marshal that little bit up to the UI. But never fear, I have my old friend, _SynchronizationContext at my disposal.
Here’s the new button Click event:
private void button1_Click(object sender, EventArgs e)
{
int max = Convert.ToInt32(txtMax.Text);
int step = Convert.ToInt16(txtStep.Text);
progressBar1.Minimum = 0;
progressBar1.Maximum = max;
int[] numbers;
MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));
Thread thread = new Thread(delegate()
{
numbers = proxy.GetNumbers(max, step);
SendOrPostCallback addListItem = delegate
{
foreach (int number in numbers)
lstNumbers.Items.Add(number.ToString());
};
_SyncContext.Post(addListItem, null);
});
thread.Start();
}
The only drawback with this technique is that as soon as the button is clicked, the user will have control of the UI returned. This may or may not be a good thing. As you can see, there’s a lot to be concerned about when you’re using WCF callback’s to update UI. The solution that immediately comes to mind to control the UI fully, is to use an asynchronous delegate instead of a Thread object. in fact, the Thread object is not a good idea anyway because it doesn’t use the thread pool and thread initiation carries a lot of weight. If I change the code to use an asynchronous delegate, I can declare the IAsyncResult object that the invoking the delegate will return, at a class level. Doing this, gives me access to the state of the asynchronous call anywhere on the form. Then I can check for the IsCompleted property before allowing other UI activity to occur.
Here’s the re-work using an asynchronous delegate instead. Notice that thanks to the Func delegate and its overloads, I didn’t need to create my own delegate for this. Also notice that true to the async delegate pattern, I use a callback method (not to be confused with the service callback) that will get fired after the task of the delegate is completed. And it is here where I’ll update my list box. The async delegate callback method gets fired on the same background thread that the delegate did its work, so I still need to marshal up to the UI thread in order to update it.
private void button2_Click(object sender, EventArgs e)
{
int max = Convert.ToInt32(txtMax.Text);
int step = Convert.ToInt16(txtStep.Text);
progressBar1.Minimum = 0;
progressBar1.Maximum = max;
MyDuplexClient proxy = new MyDuplexClient(new InstanceContext(this));
Func<int, int, int[]> proxyCall = new Func<int, int, int[]>(proxy.GetNumbers);
asyncProxy = proxyCall.BeginInvoke(max, step, ServiceCallComplete, proxyCall);
}
void ServiceCallComplete(IAsyncResult ar)
{
Func<int, int, int[]> proxyCall = (Func<int, int, int[]>)ar.AsyncState;
int[] numbers = proxyCall.EndInvoke(ar);
SendOrPostCallback addListItem = delegate
{
foreach (int number in numbers)
lstNumbers.Items.Add(number.ToString());
};
_SyncContext.Send(addListItem, null);
}
Now from anywhere else in the form where a user action might take place, I can check the service call thread like this:
private void btnClear_Click(object sender, EventArgs e)
{
if (_AsyncProxy.IsCompleted)
{
lstNumbers.Items.Clear();
progressBar1.Value = 0;
}
}
As you can see, using WCF callbacks, while easy, is not trivial when the work you want to do back at the client is UI related. The first thing you should always ask yourself is, “do I really need to do this?”. There’s a lot of details to take care of and even then, you may not get the effect that you would like. In this last example, pressing the Clear button will simply do nothing. In reality, you may want to disable controls on the form while the service call is taking place. See, there’s quite a lot of worry about.
Until next time…
I want to show you something that many of you may be familiar with since it’s really not new to .NET 4 (well not all of it anyway). Be that as it may, I think it falls into the category of “still not too regularly used”. The technique I’m going to show you has to do with Lambda expressions in my examples but can certainly be accomplished with anonymous delegates. I’m not here to show you an intro to Lambda expressions, but instead how to mix them with the Action<T> and Func<T> delegates for some cool coding techniques. But first, an introduction to these delegates: The oldest and simplest is Action<T>. This delegate was introduced back in .NET 2.0 and could be used with anonymous delegates. The signature of this delegate is:
public delegate void Action<T>(T arg);
With this pretty free-form signature, the delegate is pretty useful in any scenario where you need to define methods with single signatures. Later after my introduction, I’ll show you how to use this delegate in a cool technique. Now, in .NET 4 Microsoft proved that their developers watch entirely too much Mythbusters, by falling into the creed of “What’s worth doing, is worth over-doing”. I’m not being critical here; I fall into that one all the time myself. In .NET 4, Microsoft expanded on the Action<T> idea and came out with Action<T1, T2>. How’s that overdoing it you ask? Well gentle reader, that’s not the overdoing part, this is: Action<T1, T2, T3>, Action<T1, T2, T3>, and Action<T1, T2, T3, T4>. If you still think that’s not too much, it actually goes out to T8.
The signatures of these delegates are as you may guess, the same as the original but with additional arguments. For example:
public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
I guess you can call this a “one size fits all” delegate.
Also in .NET 4 came the introduction of the Func<TResult> delegate. The signature of this delegate looks like this:
public delegate TResult Func<TResult>();
There’s also one that accepts a single argument called, Func<T, TResult>, whose signature looks as follows:
public delegate TResult Func<T, TResult>(T arg);
And as you can guess, there are others. Specifically, Func<T1, T2, TResult> and so on all the way to T8 as well.
From what you can see here, the difference between the two delegates is that Action does not offer a return type and Fun does. So what’s this good for? Let me show you.
I’ll start with the Action delegate since its lack of return type make for a bit simpler example. The Action delegate lets you assign a piece of code to a variable for later invocation. The type(s) defined in the generic determine the types of the arguments you use in either an anonymous delegate or a lambda expression. For my examples, I’m going to use lambda expressions and keep things current. Check out this code sample:
Action<IProcessable> process = (processable =>
{
processable.PerformSomethingHere();
foreach (var item in processable.SubItemList)
{
item.DoSomethingWithItem();
}
});
This code is designed to act upon any object that implements the IProcessable interface. It simply calls a method defined by that interface then looks through a list property called SubItemList, which is also defined in the interface. On each item in the list, it calls a method on that item. This idea will be very similar to simply putting this code in its own method, then calling that method with any implementation of IProcessable. However, if you have no need to use this code from multiple outside methods, yet still have to call it multiple times (as you’ll see in a second), defining it this way makes for great encapsulation and isolation. So not let’s say I have an object hierarchy that looks something like this:
Parent.Children[x].GrandChildren
In other words, the Parent object has a collection of Child objects in a property called Children, and each child object has a collection of GrandChild objects in a property called GrandChildren. The Parent, Child, and GrandChild classes all implement the IProcessable interface so I need to execute the code snippet you saw above on all these objects. As I said, it’s easy enough to put the above-code in a method and just called that method from a for-each scenario on my Parent object, but I won’t need that code called from anywhere else and I want to keep all this encapsulated in my one method. I can use the processable variable and invoke it, sending into its argument any instance of the IProcessable interface. The solutions is to do something like this:
Action<IProcessable> process = (processable =>
{
processable.PerformSomethingHere();
foreach (var item in processable.SubItemList)
{
item.DoSomethingWithItem();
}
});
process.Invoke(Parent);
foreach(var child in Parent.Children)
{
proces.Invoke(child);
foreach (var grandChild in child.GrandChildren)
process.Invoke(grandChild);
}
As you can see, the solution is simple and elegant and eliminates the need to have yet another method in your class. If I wanted to pass in another value, like a boolean, into each invocation of the code snippet, I can use the Action<T1, T2> delegate. the lambda expression would then have two variables in it. Here’s the same code modified I the way I’ve just described:
Action<IProcessable, boolean> process = ((processable, b) =>
{
processable.PerformSomethingHere();
foreach (var item in processable.SubItemList)
{
item.DoSomethingWithItem();
item.BooleanPropertu = b;
}
});
process.Invoke(Parent, false);
foreach(var child in Parent.Children)
{
proces.Invoke(child, true);
foreach (var grandChild in child.GrandChildren)
process.Invoke(grandChild, true);
}
It’s very important to wrap the two arguments prior to the lambda’s “goes to” operator using parentheses. Pretty cool huh? Yeah, I think so too . Let’s take a look at using the Func delegate in a very similar fashion. Remember, this delegate defines a return type as well.
The usage scenario for this delegate would be pretty much identical as the previous, only you would have the need to return a value from the invocation. So this time, let me share with you a real-world example on where I’m currently using this delegate. First let me set the scene.
I have a situation where I have to obtain three different database schema query filters (strings) from an incoming dictionary of key-value pairs (IDictionary<string, string>). The dictionary comes into a method and potentially contains three items keyed by “TableFilter”, “CommandFilter” and “ViewFilter”. I say potentially because the incoming dictionary may not contain all of these keys, or none at all, but those that are present contain values that are needed in individual variables. So for example, under normal, boring code circumstances, I would need to check the incoming dictionary (a variable called arguments) to see if it contains the key TableFilter. If it does, I set its value in a string variable called stringFilter. I need to repeat this for the other two keys I’m looking for. Oh, and did I mention that the arguments variable can come into my method as null as well? And, if either the key is not found in the dictionary or the entire dictionary comes in as null, I still need my string variable(s) but with an empty string as their value.
Fine, you’re thinking I can simply check arguments for null first, then do a “contains” check on each key and then set each variable accordingly. Man would that be boring! Let’s do it in a much cooler way:
Func<string, string> filterCheckAndSet = (key =>
{
string filter = "";
if (arguments != null && arguments.ContainsKey(key))
filter = arguments[key];
return filter;
});
string tableFilter = filterCheckAndSet.Invoke("TableFilter");
string commandFilter = filterCheckAndSet.Invoke("CommandFilter");
string viewFilter = filterCheckAndSet.Invoke("ViewFilter");
Here, you can see I’m defining my code snippet in a Func<T, TResult> delegate type, where the first generic defines what I’m sending into the code and the second defines what I’m returning. As you can see, I default my return-type to an empty string, I check the dictionary against it being null and also containing the key I need. The key is one of the arguments I will send into the piece of code. If I find the key, I set the my return variable to the contents of that dictionary item and then return it; yes I can do a return inside code defined in a Func delegate type. Later, I simply invoke the filterCheckAndSet variable, sending in each key, and using the return value in each string variable I need.
That’s it. I’ve found myself using these techniques more and more. But remember, the biggest argument you’ll find against this is that you can accomplish the same with additional method calls. My argument is, yes you can, but if you don’t need a specific level of code re-use, try to limit the scope of the code as it provides better encapsulation. Also, remember that the code snippets are stored in object variables so they can be passed around anywhere you want (should you actually have that particular need).
Until next time…
Note: Using a Console app for hosting should be done for development only ! Now that the disclaimer is out of the way, I currently doing some development work for a customer and I had the need to know every time any of my services receives a call. Since I do my development using a console application for service hosting, it was easy enough to write out to the console from each service operation. Of course, putting code in every method was possible but not only would it be time consuming, to turn it off later would be a pain. The answer needed to be something that gets hit on every operation. Since WCF is essentially one giant inversion of control container, I knew there was a point I could tap into before any operation call. Enter behaviors ! This turned out to be a multi-step process but once it’s in my library of WCF stuff, I can reuse it and it actually turned out to be quite cool. I’ll explain each step and the reasons for the step.
Step 1 – Write a custom Parameter Inspector The first class you need to write is one that implements the IParameterInspector which is in the System.ServiceModel.Dispatcher namespace. This class will later be installed in such a way that it gets hit on every operation call. The operation name is one of the arguments you have access to, as well as all the operation arguments which I don’t need in this case. The methods in this implementation are BeforeCall and AfterCall, and it is the BeforeCall that I’m interested in. The code I’ll place in this method very simply outputs something out to the console using Console.Writeline. Unfortunately the name of the service is not passed into this method so I need to get that into this class using a custom constructor; you’ll see how I’ll get it to the class later. Here’s the code for my ConsoleReportInspector class: public class ConsoleReportInspector : IParameterInspector
{
public ConsoleReportInspector(string serviceName)
{
_ServiceName = serviceName;
}
string _ServiceName = string.Empty;
void IParameterInspector.AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
{
}
object IParameterInspector.BeforeCall(string operationName, object[] inputs)
{
Console.WriteLine(string.Format("{0} - '{1}.{2}' operation called.", DateTime.Now.ToLongTimeString(), _ServiceName, operationName));
return null;
}
}
Step 2 – Install the class using an Operation Behavior
In order to install the parameter inspector, I’ll need to write a custom operation behavior class. This is a class that implements the IOperationBehavior interface. You need to remove the throw to NotImplementedException from all the methods; and the method of concern here is ApplyDispatchBehavior.
The name of the service being called is accessible through the Parent property of the dispatchOperation argument. I need to instantiate my ConsoleReportInspector class and send the service name into the constructor I added earlier. Afterward, I just need to add my parameter inspector class to the list of parameter inspectors accessible in this behavior.
I also inherited this class from the System.Attribute class so I can use it as an operation behavior attribute on individual operations if I wanted. This is just for flexibility since I plan on hooking this into a service so it affects all operations.
Here’s the code for my ConsoleReportOperationBehaviorAttribute class:
[AttributeUsage(AttributeTargets.Method)]
public class ConsoleReportOperationBehaviorAttribute : Attribute, IOperationBehavior
{
void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
}
void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
}
void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
string serviceName = dispatchOperation.Parent.Type.Name;
dispatchOperation.ParameterInspectors.Add(new ConsoleReportInspector(serviceName));
}
void IOperationBehavior.Validate(OperationDescription operationDescription)
{
}
}
As-is, I can simply decorate a service operation with [ConsoleReportOperationBehavior] and if hosted on a console application, you’ll see output to the console when the decorated operation is called.
Step 3 – Install the operation behavior on all operations using a Service Behavior
Next I need to write a service behavior. This is a behavior that gets installed when the service loads (the host is opened). The job of this behavior is to install my operation behavior on all the service operations. A service behavior is a class that implement the IServiceBehavior interface. Like before, I’ll remove the exception calls and once again the method I’m interested in is ApplyDispatchBehavior.
I’m going to iterate through all the endpoints of this service, which are accessible through the serviceDescription argument, and for each endpoint I will iterate through the operations of the contract of each endpoint. To each operation I will add an instance of my ConsoleReportOperationBehaviorAttribute class.
This class too I will inherit from Attribute so I can use it to decorate a service in the case that I wanted to take this approach at some time.
Here’s the code for my ConsoleReportServiceBehaviorAttribute class:
[AttributeUsage(AttributeTargets.Class)]
public class ConsoleReportServiceBehaviorAttribute : Attribute, IServiceBehavior
{
void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
foreach (OperationDescription operation in endpoint.Contract.Operations)
operation.Behaviors.Add(new ConsoleReportOperationBehaviorAttribute());
}
void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
Step 4 – Apply the service behavior to any service I want programmatically at the host
Whatever approach you take to hosting, all you need to do is access each instance of ServiceHost and add the service behavior to the list of behaviors in the host. I have my own techniques for hosting which include some custom declarative stuff to allow me to turn hosting on and off at will through config. I also like to separate the accumulation of my ServiceHost instances from the actual application that will do the hosting. This way I can move it to a Windows Service when I’m ready to go to production.
Here’s the code that installs the behavior:
ConsoleReportServiceBehaviorAttribute behavior = serviceHost.Host.Description.Behaviors.Find<ConsoleReportServiceBehaviorAttribute>();
if (behavior == null)
host.Description.Behaviors.Add(new ConsoleReportServiceBehaviorAttribute());
The host variable is an instance of ServiceHost. I perform the code above in between a config check so I can toggle it off at will.
The end result is quite cool since when turned on, every call to any of your services will be shown on the console.
Until next time…
WCF 4.0 incorporates the features previously only obtainable via the REST Starter kit for .NET 3.5. Among the features included is the ability to cache REST requests using a similar technique to caching ASP.NET pages. The 4.0 version of the System.ServiceModel.Web assembly includes an attribute called AspNetCacheProfile which takes a string as an argument. The attribute is to be used on a service contract operation as follows: [OperationContract]
[WebGet(UriTemplate = "/{name}/getGreeting.xml",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml)]
[AspNetCacheProfile("CacheFor10Seconds")]
string GetGreetingXml(string name);
The string points to a cache profile to be defined in the config section as follows:
As you can see, this is pretty much identical to setting up cache profiles for ASPX pages. The effect is pretty much what you would expect, the caching of a REST request. This can be proven and tested by implementing the above contract as such: public string GetGreetingXml(string name)
{
return string.Format("Hello {0}. The time is {1}", name, DateTime.Now.ToLongTimeString());
}
Now you can refresh the request and you’ll see the same time for 10 seconds before it changes; once again, the same effect as in caching an ASPX page.
So what did I learn the hard way you ask? Well, common sense dictates that the request go through ASP.NET in order to use its caching capability. This not only means that you have to host in IIS or WAS, but also that you need to turn on ASP.NET compatibility mode. This shifts the processing of the REST request over to an HTTP handler that also sets an HTTP Context for you, something not normally done with conventional IIS hosting for REST services. To turn this on, you must enable it in the section under the section using the aspNetCompatibilityEnabled attribute. Not only that, but you have to “allow” it on the service using the AspNetCompatibilityRequirements attribute.
This part was not a surprise for me since I was already familiar with this technique and the added scope your service receives because it. I’m referring to the entire HTTP Context including session, application, cache, etc. Keep in mind that this is not for everything and should be used in very specific scenarios as it ties the service to the hosting style quite tightly.
What drove me crazy is something I’m surprised I did not notice in the past and that is the fact that your REST requests will not work while using the Visual Studio development server. Meaning you need to create an application in IIS and run it that way. No big deal but it drove me a little crazy since the meta data exposure worked fine, and so did the new HTML Help pages (another new feature in WCF 4.0 For REST). But the second I tried to request one of my URLs, it bombed out. Once I set up my application under IIS, everything was fine.
I have to give credit where it’s due and thank Jon Flanders. I found the answer in his book Restful .NET from O’Reilly press.
Until next time…
In the never-ending quest to keep my site up-to-date, I wanted to add a “latest tweet” area to the top of my blog. All these tweakings I’ve done (the syntax highlighter, licensing, branding, etc) were actually inspired by a talk that Scott Hanselman made in Cairo Code Camp on making your blog suck less. The talk is based on this posting he made some time ago. I’ll post on all the tweakings I’ve done later; let’s get back to the Twitter feed. The Twitter site self has a section where you can step through creating an embedded Twitter feed, either in Flash or HTML. In fact if you Google or Bing the phrase “embed twitter feed on website”, you’ll see many different techniques. The one I used is the one right off the Twitter site. After walking through the wizard, the site gives you this code: <div id="twitter_div">
<h2 class="sidebar-title">Twitter Updates</h2>
<ul id="twitter_update_list"></ul>
<a href="http://twitter.com/miguelcastro67" id="twitter-link" style="display:block;text-align:right;">follow me on Twitter</a>
</div>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/miguelcastro67.json?callback=twitterCallback2&count=5"></script>
I first inserted this code as-is, just to get things working (my usual approach to things). The div tag was inserted into my homeTemplate.blogTemplate in the area where I wanted to display my Twitter feed. In my case, this was just below the area that shows the admin bar (shown only when logged in). The two script tags need to be placed at the bottom of the same file, just above the closing body tag. This displayed my last five tweets in a unordered list. The first script tag includes the function that the Twitter site will call back to after retrieving my feed information. The second script tag makes the call to the Twitter API and defines the name of the callback function defined in the first script. This worked fine but I wanted a different look.
The first thing I did to modify the display is to browse to the http://twitter.com/javascripts/blogger.js link and place the function in a javascript file in my site; then I replaced the src attribute in the first script tag to point at my function. The results of this of course were no different than before – good.
Next I modified the div section for my display to look like this: <div class="twitter-div">
<a class="twitter-header" href="http://twitter.com/miguelcastro67" alt="Follow me on Twitter">Last Tweet:</a>
<span id="twitter-post" class="twitter-post"><i>retrieving last tweet...</i></span>
</div>
<br/>
As you can see, I eliminated the unordered list and replaced it with something more simple, that’s one line only, and that expects only one tweet. Then I took the function I had obtained from the blogger.js file and modified to look like this: function twitterCallback(twitters)
{
var statusHTML = [];
var username = twitters[0].user.screen_name;
var status = twitters[0].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
return '<a href="' + url + '">' + url + '</a>';
}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
});
statusHTML.push('<span>' + status + '</span> - <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[0].id + '">' + relative_time(twitters[0].created_at) + '</a>');
document.getElementById('twitter-post').innerHTML = statusHTML.join('');
}
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
if (delta < 60) {
return 'less than a minute ago';
} else if (delta < 120) {
return 'about a minute ago';
} else if (delta < (60 * 60)) {
return (parseInt(delta / 60)).toString() + ' minutes ago';
} else if (delta < (120 * 60)) {
return 'about an hour ago';
} else if (delta < (24 * 60 * 60)) {
return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if (delta < (48 * 60 * 60)) {
return '1 day ago';
} else {
return (parseInt(delta / 86400)).toString() + ' days ago';
}
}
Now I only worry about one tweet and display information about that tweet into the inner section of the span tag called twitter-post. Incidentally, the original callback function looked like this: function twitterCallback2(twitters) {
var statusHTML = [];
for (var i = 0; i < twitters.length; i++) {
var username = twitters[i].user.screen_name;
var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
return '<a href="' + url + '">' + url + '</a>';
}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
});
statusHTML.push('<li><span>' + status + '</span> - <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '">' + relative_time(twitters[i].created_at) + '</a></li>');
}
document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}
Obviously I changed the name in the call to the Twitter API to use the callback function twitterCallback instead of the original twitterCallback2, but of course this can be anything so long as the two match.
The last change was to change the count attribute in the call to the Twitter API to 1 instead of 5. This wasn’t crucial since I was only dealing with array item 0 in my callback function, but in the interest of getting as much performance as possible I thought it was a good idea.
I added the style sheet tags to make the display look the way I wanted and voila. Because of the callback-nature of this technique, the blog page will render first while the call to the Twitter API is made and in the meantime I display a “retrieving…” message.
Until next time.
|