Archive for February, 2009

Twilight 1.5: Multiple Views with MVVM

You may have noticed the new look for the Twilight Twitter Badge on my blog a few weeks ago. I wanted to add a few new looks for the badge and got one of them done but then decided I need to spend some more time on it before releasing it because I didn’t like the way the code was turning out. There were a couple of things I didn’t like:

  1. The code was too tightly coupled to the views/skins. This made it hard to add new views/skins without duplicating code.
  2. The views/skins weren’t blendable at all.

To start my rework I began with this post by the Expression Blend/Design team on simulating sample data in Blend. The post is a very simple yet workable solution for displaying design time data in Blend so that you can work on the layout of your application. The only change I made was how I detected design mode. After playing around with that sample I decided that to implement this in Twilight I would need to switch to a Model-View-ViewModel approach so I started doing some research into using this approach with Silverlight. In my research I came across this post by Ryan Keeter on using MVVM in Silverlight. It was a nice simple explanation that made sense to me so I set out to combine the expression team example and this MVVM example.

What I ended up with is pretty close to MVVM. I say pretty close because I don’t think it fully fits since the ViewModels hook into some of the Views Storyboard events and also control the Views VisualState transitions. Maybe that fits into MVVM, but it probably breaks some of the rules. However, for this tiny application it makes things a lot easier. I still have multiple Views per ViewModel and the Views have zero code which is what I really wanted.

There are two ViewModels that I’m using: ListViewModel and RotatingViewModel. Then on top of these two ViewModels are four Views: Default, Large, Small, and Tiny.

ListViewModel Views  

Default View

Large View

The ListViewModel is for views where there is just a list of tweets while the RotatingViewModel is for views that display a single tweet at a time.

RotatingViewModel Views  

Small

Tiny

 

 

 

 

You can switch between these views by setting the mode initParam equal to the view you want (example: mode=tiny). The Tiny view looks like the twitter counter badge but then pops the bubbles over the surrounding content. This is done using the windowless = true parameter and absolute positioning. Right now the Silverlight will float over the content below it even when the bubble isn’t showing, so you won’t be able to click through to that content. I might be able to figure out a better way to handle it, but for now that is a known limitation.

Since now all the view logic is in the ViewModel, writing tests is a lot easier. I’m still using the same Silverlight test framework, but thanks to this post by Justin Angel I added a few more complex tests using his WaitFor extension. The test coverage is still very light and I’m not testing the views at all, but I feel like I’m starting to get testing in Silverlight.

I’ve also added another option for hosting Twilight on your blog. You can now host it via Silverlight Streaming using an iframe. Add the following HTML to your page:

<iframe src="http://silverlight.services.live.com/invoke/232/Twilight1.5/iframe.html?username=[your username]&count=10&mode=small" scrolling="no" frameborder="0" style='width:200px; height:175px'></iframe>

** Hosting it via Silverlight Streaming doesn’t support the Tiny mode since the Silverlight won’t be able to expand outside of the iframe.

In addition to hosting it via Silverlight Streaming, you can always self-host it or use the xap I have hosted on dreamhost at http://twilight.bryantlikes.com/twilight.xap. If you’re already using the hosted version, you can switch the mode by using the mode initParam as I mentioned above.

Hopefully this will serve as a great twitter badge for your blog and also a decent example of MVVM in Silverlight along with some unit testing examples as well. Feel free to join the project on Codeplex and create your own views. I am still working on at least one more version that will make the colors tweakable and maybe even detect what colors should be used based on the surrounding html.


Comments Off more...

Detecting Design Mode in Silverlight

One of the things I’ve been trying to getting a better understanding of is how to make the Silverlight projects I work on more blendable:

In general, WPF and Silverlight controls should be "blendable". ItemsControls need to display representative data within the design surface.

The problem, at least for me, is that every example out there to detect design mode uses:

var designMode = !HtmlPage.IsEnabled;

Since the Html Bridge is disable inside of Blend, this does work for the most part, but what about when your xap is hosted on another server? In this case the Html Bridge is disabled by default so if someone doesn’t configure it correctly they will get your design time data.

Mode HtmlPage.IsEnabled
Blend false
Visual Studio false
Local Xap true
Remote Xap false*
Streaming Silverlight true**

* This can be changed to true, but it is disabled by default.
** Enabled by default

So I was trying to come up with another method to detect design mode in Silverlight and here is the best I have come up with so far:

public bool IsDesignTime()
{
    try
    {
        var host = Application.Current.Host.Source;
        return false;
    }
    catch
    {
        return true;
    }
}

What happens is that Application.Current.Host.Source works great when the plugin is hosted in a web page and will return the path to the xap file, but in design mode trying to access that property throws an exception. So if you hit the exception then you’re in design mode, otherwise you’re in a web page. Not super elegant but it feels better to me than checking if the Html Bridge is enabled since that isn’t a true check.

Update: As Tom mentions in the comments, you can also use DesignerProperties.GetIsInDesignMode. But if your goal is to make your project more blendable then Visual Studio support might not be important.

Mode DesignerProperties.GetIsInDesignMode
Blend true
Visual Studio false
Local Xap false
Remote Xap false
Streaming Silverlight false

So with this check worst case you get no data in the Visual Studio designer, but the Visual Studio designer isn’t that great anyway. Blend is the real goal. So instead instead of the above code you can use this code instead:

public bool IsDesignTime()
{
    return DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual);
}

Thanks for the tip Tom!

Digg This
This work is licensed under a Creative Commons Attribution By license.


Comments Off more...

Create custom LINQ providers fluently

Just released LinqExtender 2.0. Over previous release , it contains generally bugs fixes. Overall, I have focused on striping out complexity as much as possible to keep you focused on your business logic. You can see the full list of features in the documentation that comes with it.

Now, while creating the LinqToTwitter example, I have shown that creating custom providers with LinqExtender requires two steps, first you have to define a query object by implementing IQueryObject and then you have made a Query<T> successor and override few methods. In LinqExtender, object/ entity equivalent is Bucket. Starting from 2.0, there is a Fluent interface implementation of it that works as an internal DSL and gives you a single entry point for all query and update , inserts and delete, thus making things more declarative and one way.

In this post, I will show you how to generate SQL statement from LINQ query with nested where clause, using the fluent interface implementation. To start, let's consider the following query

var query = from book in bookContext
where ((book.Author == "Mehfuz" && book.ISBN == "2") || book.Id == books[2].Id) || 
(book.Author == "Paolo Pialorsi" && (book.ISBN == "100-11-777" || book.ISBN == "1"))
select book;

It's taken from the Entrypoint.cs test class that comes with LinqExtender project along with OpenLinqToSql sample ORM. Now, to do things in a very basic way. Let's first create a string builder and append the initial select.

StringBuilder builder = new StringBuilder("SELECT * FROM [" + Bucket.Instance.Entity.Name + "]");

To be precise, Bucket.Instance is the entry point for all query and object details. Moving to where statement , LinqExtender uses simplified expression tree that is exposed by Bucket.Instance.ExpressionTree. All we need to setup how the output will look like and the rest will be covered by the toolkit.

builder.Append("WHERE");
builder.Append("\r\n");
Bucket
.Instance
.ExpressionTree
.DescribeContainerAs(builder)
.Root((containter, operatorType) => containter.Append(" " + operatorType + " "))
.Begin(container => container.Append("("))
.EachLeaf((container, item) =>
 {
     string value = GetValue(item.Value);
     container.Append(item.Name + RelationalOperators[item.RelationType] + value);
 })
.End(container => container.Append(")"))
.Execute();

Here, let assume that GetValue(..) will return a formatted SQL string and ReleationalOperators is a dictionary that has mappings for item.RealtionType ( GreaterThan -> ">" , LessThan => "<", etc). Basically, as the implementation shows, we are defining the way output will be stored in the container (In this case, StringBuilder). All these code should be placed in Query<T>.Process(IModify<T> items) method and on execute it will just return the following SQL block

Select * from book 
 WHERE
(((Author='Mehfuz' AND ISBN='2') OR Bk_Id='1734') 
OR (Author='Paolo Pialorsi' AND (ISBN='100-11-777' OR ISBN='1'))) 

Extender basically knows how to get though this nested where clause. From basic computer science, it builds linked objects based on a Syntax Tree, with each parenthesis adding diversion to the tree like shown below

 image

So far, this is a very rudimentary example. With 2.0 it is also possible to build your own reusable format provider for building literals that saves repetitive code blocks for same kind of task (updating a database). This is actually just a schema builder that defines how the output will look like using the same Bucket.Instance calls. Out of the box, TSqlFormatProvider is provided.Depending under which Query<T> method it is used; it will generate insert, update, delete or select statement where all you have to call Bucket.Instance.Translate(...).

string sql = Bucket.Instance.Translate(new TSqlFormatProvider());

This enables you to build not only your own LINQ to Anything format providers but also share it with the community to reuse what is already out there. More information on how to get started can be found at the project documentation.

In a word, Bucket.Instance is all you need to go through and build your own LINQ provider. Optionally, you can override the following methods (under Query<T>) to give your provider various OTS (Object tracking service) support .

1. AddItem () - called during SubmitChanges() call for new object.
2. RemoveItem () - called during SubmitChanges() call for Delete.
3. UpdateItem () – called during SubmitChanges() call for update.

I have updated Creating LinqToTwitter using LinqExtender post with the latest release. You can get a copy of the latest 2.0 release from www.codeplex.com/linqextender,  and of course as usual all your feedbacks are really helping to shape the toolkit.

Hope that helps,

Update on 28th Feb 2009, with new patch for Bucket.Instance.ExpressionTree

kick it on DotNetKicks.com
Comments Off more...

Controlling Single Web Parts with CSS Article Posted

I often get questions about how can a particular web part be branded separately from all the rest or be branded by type.  For example you want every Contacts list to have a green header bar instead of a tan header bar.  Or perhaps you want a column of web parts on a page to look different than the main area that contains other web parts.

The latter I have always had a solution for, the former I figured out something today.  As with everything that I focus on, these are "no custom development" / "no .NET code" solutions. You can usually build whatever customization you need with custom code.  If you would like to just rely on CSS however, here you go....

Controlling Single Web Parts with CSS


SharePoint Online – a solution for SharePoint hosting for small businesses

I recently got a question from James in Australia about the challenges small institutions face with using and deploying SharePoint.  I know a lot of people are in this position where they want to use SharePoint but don't have the resources to support hosting it internally.   You can check out Microsoft Online Services, they offer SharePoint hosting via SharePoint Online.   http://www.microsoft.com/online/sharepoint-online.mspx 

Hope this helps, thanks James!


  • Sponsored Links

  •  

    February 2009
    M T W T F S S
    « Jan   Mar »
     1
    2345678
    9101112131415
    16171819202122
    232425262728  
  • .

    Copyright © 1996-2010 Answer My Query. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress