Couple of weeks back,  I introduced the Slex Project. And thanks to the Christmas holidays; today I checked in the Preview 2 of Slex. Here are few cool features in Slex Preview 2. You can download the same here from CodePlex – http://slex.codeplex.com

 

What is there in Slex?

If you are familiar with Silverlight/Expression Blend, you should be knowing about the System.Windows.Interactions infrastructure – which provides various Behaviors, Triggers and Actions. Slex is an experimental implementation of some additional triggers and actions on top of the same, along with few extension points.

image

 

Triggers in Slex, and actions inside them, can be invoked based on conditions

image

These are some notable aspects in Slex, that are not available in the triggers and actions available with Expression Blend.

  • Slex allows you to define multiple conditions for invoking triggers (like you can specify a KeyDown event trigger should be fired only if ‘A’ is pressed)
  • You can specify multiple conditions for invoking each action in a trigger
  • Slex introduces few more Triggers and Actions that you’ll see soon.

As of now, Slex Preview 2 Provides the following Triggers

  • EventTrigger – Will be fired when an event is raised. Can listen to events of Elements, or events from your view model
  • PropertyTrigger – Will be fired when the specified property changes. Can listen to properties of Elements, or property in your view model
  • ReactiveTrigger – Can ‘import’ an Observable that you may ‘export’ using MEF. Useful to define and use custom events using System.Reactive.

And the following actions

  • InvokeMethodAction – Invoke a method directly in the View model or for a target element, supports passing parameters via Xaml
  • InvokeCommandAction – Invoke an ICommand in the view model
  • StoryBoardAction – Start, Stop, Pause, Resume, or Reverse story boards
  • PropertyAction – Sets a property value (very crude as of now)

You can specify one or more InvokingCondition for triggers and/or actions. Also, actions like InvokeMethodAction and InvokeCommandAction has an ActionParameters property, so that you can pass one or more Parameters when invoking methods and commands.

 

Conditionally Invoking Triggers and Actions

Let us see a simple example on a scenario – You need to start a story board when a button is pressed, but you need to do that only if a particular checkbox is checked. Assuming your Button is btnBegin, your StoryBoard is myStoryBoard and your checkbox is chkMain, this is something that you can do. (See the StoryBoardAction demo)

image

If you see the above code, you may find that we are specifying various conditions for the trigger itself – all Actions in the Trigger will fire only if all Invoking Conditions are True. You should be able to place other Actions (that comes with Expression Blend, you own custom actions etc) with in an EventTrigger, PropertyTrigger or ReactiveTrigger – to execute them conditionally.

Also, you may need to specify conditions for invoking each Action in the trigger individually. You can do this as well. For example, the following Property Trigger will execute only if the Text property of the Textbox txtData is Hello, and the checkbox myCheckBox is checked.

image

 

Better MVVM - Invoking Methods and Commands in your View Model and Passing parameters

Have a look at the InvokeMethodAction and InvokeCommandAction (see the demo). There are some changes for these actions from Preview 1.

InvokeCommandAction let you invoke a method against the view model. Assume that you’ve a list box named userList - here is a simple example on how to execute a command when ever the selection is changed, and you can specify a parameter for your ICommand using the ActionParameter. In fact, you can pass more than one ActionParameter – and in that case, they will be passed as an object array to the CanExecute and Execute methods in your command.

 

image

And here is something more interesting - InvokeMethodAction. You can use InvokeMethodAction to invoke methods in your view model directly. Assume that you have a UI with two text boxes and a button, and you’ve an Add method in your view model that takes two arguments of type integer. This is what you need to do to invoke your Add method, when the user clicks the button btnName.

image

 

ReactiveTrigger – Decoupling Triggers with the help of MEF and System.Reactive

One interesting addition in this preview is the ReactiveTrigger. ReactiveTrigger let you import an Observable you exported from some where else. This will let you create customized user input triggers pretty quickly. I’m not going to the implementation details, but assuming you are already familiar a bit with MEF concepts and System.Reactive concepts, here is what you can do (See ReactiveTrigger demo in the Slex.Lib.Demo for entire source code)

Step 1 – Some where in your host application, Create a trigger and export it

Your exported method should match the signature Func<object,IObservable<EventResult>>. You can use the ObservableExport attribute in Slex.Lib to mark your trigger as an exportable part. Also, the name you provide to the ExportName attribute will be later used in Xaml to ‘import’ this trigger.

image

Step 2 – In your application startup, call Compose method in SlexPartComposer, and pass your catalogs

In this case I’m simply passing and assembly catalog with the current assembly, because I’ve my trigger as part of my host app. And I’ve this line in the App.xaml.cs constructor.

image

Step 3 – Just use the trigger in your Xaml

Here we go, you can import the exported trigger, and this will get fired when ever a key is pressed.

image

 

Using Slex with Blend

You should be able to use Blend to modify most Slex triggers and actions. For example, let us see how the above Event Trigger and related action parameters will look like in Blend. You may find that you can modify the Conditions and Parameters of a trigger from with in Blend (Well, they are AttachableCollections to be precise :)).

 

image

 

 

How Slex relates to the already available Behaviors, Triggers, and actions that comes with Expression Blend?

As mentioned earlier, Slex is built on top of System.Windows.Interactions infrastructure, and you will be able to use mix and match existing Expression Blend behaviors, triggers and actions along with Slex triggers and actions.

There are few overlapping areas – For example, Slex has its own implementation for some triggers like EventTrigger, that provides some ‘extra’ features when compared to Blend’s EventTrigger.

 

Slex is very much in a preview stage, and I’ll continue hacking on this with respect to my time.

Shout it
Read more >>

K-MUG (Kerala Microsoft Users Group) Meet - Dec 19th 2009, Tvm

Plan to attend the K-MUG UG Session, this Dec 19th, Technopark, Kerala. Along with Praveen and Ratheesh, I'll be talking about C# 4.0, .NET Reactive Extensions, and Managed Extensibility framework.

Details below.






Date/Time: 19-Dec-2009 @9:30 AM- 12:30 PM



Venue:
UST Global, Bhavani,
Technopark, Trivandrum, Kerala

Speakers & Topics

Ratish Naroor

Senior .NET Developer / SEO Expert

Social Media

Search Engine Optimization / Search Engine Marketing
Social Media Marketing
Blogging

Anoop Madhusudanan

Solution Architect at UST Global

C# 4.0 and Silverlight


VS2010 + C# 4.0 features, including dynamic programming
LINQ to Events
Managed Extensibility framework
Silverlight 4.0 features.

Registration:
Event is Free, but limited seats. Please register here and ensure you bring the confirmation ticket.




Read more >>

For the last couple of week ends, I was hacking around Silverlight interactions and behaviors. Mainly, the objective was to learn the Interactivity system in depth, and in the process, I’ve done few interesting hacks.

And thus born Slex project, Silverlight Experimental hacks. :). Slex is built on top of System.Windows.Interactivity framework, and supports a couple of interesting Triggers and Actions.

Note: Slex is updated. Please read Slex For Silverlight Preview 2

This is the intro screen of the related demo, and I’ll explain a bit on each item. The download link is towards the end of this post.

 

image

 

As an introduction, here are few cool things you can already do with Slex.

1 – Simple example of an Event Trigger in Slex

Assume that you need invoke a command, when an event is fired. You can do the same by hooking up an InvokeCommandAction inside an EventTrigger (Note that this EventTrigger is a custom implementation in Slex namespace).

 <i:Interaction.Triggers>
            <slex:EventTrigger ElementName="txtData" EventName="KeyUp">
                <slex:InvokeCommandAction CommandName="UpdateDataCommand" />
            </slex:EventTrigger>
        </i:Interaction.Triggers>
Alright, I hope that looks cool. Now, what if you want to invoke the command if and only if a check box (named myCheckBox) is checked, and the user is pressing the 'A' key? Here we go.
 <i:Interaction.Triggers>
            <slex:EventTrigger ElementName="txtData" EventName="KeyUp">
                <slex:InvokeCommandAction CommandName="UpdateDataCommand">
                    <slex:InvokingConditions>
                        <slex:InvokingCondition Property="Argument.Key" Value="A"/>
                        <slex:InvokingCondition ElementName="myCheckBox" Property="IsChecked" Value="True"/>
                    </slex:InvokingConditions>   
                </slex:InvokeCommandAction>
            </slex:EventTrigger>
        </i:Interaction.Triggers>

2 – Simple example of a Property Trigger in Slex

Now, what if you want to fire a command, when a property of an element (or even a property in your View Model changes)? Here we go. You can do the same by using PropertyTrigger.

 <i:Interaction.Triggers>
            <slex:PropertyTrigger ElementName="txtData" Property="Text">
                <slex:InvokeCommandAction CommandName="UpdateDataCommand">
                    <slex:InvokingConditions>
                        <slex:InvokingCondition Value="Hello"/>
                        <slex:InvokingCondition ElementName="myCheckBox" Property="IsChecked" Value="True"/>
                    </slex:InvokingConditions>
                </slex:InvokeCommandAction>
            </slex:PropertyTrigger>
        </i:Interaction.Triggers>

 

As you can see, this will fire your UpdateDataCommand, when the Text Property changes. Also, you may or may not specify the conditions for the PropertyTrigger, just like we did for the EventTrigger.

3 – Simple example of InvokeMethodAction

In the previous examples, we’ve seen how to use InvokeCommandAction to invoke an ICommand in your view model. What about Invoking methods directly in your View Model? Here we go. Consider the following view model, that has a simple Add method to add two numbers.

image

Now, this is how to Invoke Add, so that ‘Data’ will get updated. Here is the UI and the XAML part.

image

As you can see, we have two text boxes where the user can enter the value, and a button where the user clicks to invoke the Add operation. Let us see the Xaml for this.

image

You may notice that, we are sandwiching an InvokeMethodAction inside an EventTrigger for the button click, and specifying the parameters in the order expected. Please note that the number of parameters should match the number of arguments of your Method.

Also, you can either tie your MethodParameterValue against properties of any other UI Element, or may point it to the view model. (Check out the SourceType property of MethodParameterValue).

Concepts - Brief Overview

Presently Slex supports a couple of triggers including

  • EventTrigger – You can tie an event trigger against an element, or against your view model. Fired when an event is raised
  • PropertyTrigger – You can tie a PropertyTrigger against an element’s property, or against a property in your view model. Fired when the property value changes

Also, Slex has a couple of abstract classes, including EventBasedTrigger and ObserverTrigger, and you may use the ObserverTrigger to create custom triggers that make use of System.Reactive extensions. More later.

You can sandwich Actions inside your Triggers. Few actions presently available are

  • InvokeMethodActionInvokes a method in your view model, or a method of a UI Element. You can have a collection of Method parameters in your InvokeMethodAction. See example below.
  • InvokeCommandActionInvokes a command in your view model

All Slex actions supports a set of Invoke Conditions, where you can specify multiple conditions for Invoking the commands.

Conclusion

About the source code - A first source drop is available at http://slex.codeplex.com. Go and click the Download link. Presently the drop is a VS2010 project, but you should be able to make the code run in VS2008 as well, by copying the source files and doing a bit of hacking, and modifying the references here and there.

This is a very very crude version, almost a POC. There are lot of things to do (there are quite a few bindings getting created as of now :)), lot of optimizations to be done, lot of unit tests to be written (I know, there is a suicidal absence of unit tests as of now). Also, I still need to see how this works with Blend :(.

I was talking to Vin for some time about this, and thought I’ll push the first cut any way. And also, blame Jeff too a bit.

I’ll blog soon on some other enhancements I’ve in mind, so follow me in twitter. Also, I’ll explain further few hacks I made around the Rx API, and the Dependency property listening side, by next week end. Happy Coding!!

Shout it
Read more >>

Wow, the new Bing Maps (beta) Rocks. First impressions here

I was about to sleep, but just stumbled up on Bing’s new Silverlight Powered Map site. Really cool interactive features there. Once quick thing I noticed is the integration of apps like Photosynth with the Bing maps, along with a lot of location sensitive information like local tweets, traffic information etc, overlaid in a great way. To start with, I just started searching Chicago.

image

And clicked the image thingy in the left panel, and that opened a photo synth, to display a perspective 3D Photosynth of Chicago.

image

And more surprises. Click on that orange ‘>’ button (bottom right on the left panel), and Bing will show you the Map Apps you can add to your Map (Map Apps). This includes various apps, including a restaurant finder, a real time twitter updates viewer in the map in that location, a traffic land app to view live traffic etc, a current traffic app to show the traffic status etc..

image   image

I just enabled a couple of them, including Twitter maps, Current traffic etc, and found that Mitchmaddox had a meeting with some one, and he should have started really early to get there, because the red lines shows high intensity traffic. Also, found that along with the Automatic, Road, Aerial and Bird’s eye views, Bing also provides overlaying content like tweets, on top of the Street view. Now this is cool, I can just look around and see what people are doing here.

  image image

This is just a quick post, probably there are lot more features there to explore. Here is a post from Bing team. Also, get Bing for your mobile here

Shout it
Read more >>

I was digging a bit around Silverlight Dependency properties, mainly to see how to receive change notification when ever a dependency property is changed. In WPF, this is straight forward, you may use the DependencyPropertyDescriptor, and call AddValueChanged. Like this.

DependencyPropertyDescriptor desc = 
  DependencyPropertyDescriptor.FromProperty
    (UIElement.VisibilityProperty, typeof(UIElement));

desc.AddValueChanged
  (this.myLabel, new EventHandler(VisibilityChanged));

 

Now, how to do this in Silverlight? I roamed around a bit, but can't really find a good way of doing that. So, here is a quick hack. The trick is to use DependencyProperty.RegisterAttached(..) to instantiate a dependency property type (Ahem). This is what we are doing below.

  • Create a binding with the FrameworkElement as the source
  • Use DependencyProperty.RegisterAttached(..) to create a DependencyProperty instance
  • Use FrameworkElement.SetBinding(dp, binding) to associate the dependency property with the element, via the binding.

So, we’ll get a call back when ever the dependency property changes. The RegisterForNotification summarizes what I explained above.

         
        /// Listen for change of the dependency property
        public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
        {

            //Bind to a depedency property
            Binding b = new Binding(propertyName) { Source = element };
            var prop = System.Windows.DependencyProperty.RegisterAttached(
                "ListenAttached"+propertyName,
                typeof(object),
                typeof(UserControl),
                new System.Windows.PropertyMetadata(callback));

            element.SetBinding(prop, b);
        }

 

Create a new Silverlight project, and add the above code to the code behind. And add the following controls to your xaml page..

   <Grid x:Name="LayoutRoot" Background="White">
        <TextBox Text="hello" x:Name="txtMain" />
        <Slider Value="10" Minimum="0" Maximum="100" x:Name="sliderMain"/>
    </Grid>

 

Now, just call RegisterForNotification from where ever you need (I’ve it in the Constructor of my MainPage.cs, just under the InitializeComponent() call), like

//Shows a message box when the text of Textbox or value of Slider changes.

RegisterForNotification
	("Text", this.txtMain,(d,e)=>MessageBox.Show("Text changed"));
RegisterForNotification
	("Value", this.sliderMain, (d,e) => MessageBox.Show("Value changed"));

 

Fire up your project, and you’ll see the message boxes when ever the value change happens. So, now it looks pretty interesting, I guess. Opens up possibilities like having Data triggers in Silverlight, probably via an attached behaviour. Need to evaluate the pros and cons of this approach, came across this scenario while doing some other hacks. What do you think?

Stay tuned, follow me on twitter.  Happy Coding!!

Shout it
Read more >>

top