Live Framework CTP #5 – .NET: Data hierarchies and LiveItem types

Hierarchies of data entries – the problem

As stated before, when programming against the Live Framework libraries in .NET, all data entries are located on one level below the according data feed. This very often doesn’t correspond with a programmer’s expectations, when he has a hierarchy of data entries, e.g. a hierarchy of data folders and files. As programmer you want to have a tree-like view on this data to work with it. Unfortunately, in the current LiveFx CTP this was not made possible directly.

Extending DataFeed and DataEntry

The solution for this is not far away. A data entry’s resource has got an Id and a ParentId as properties, over which one can identify and associate an entry’s parent and its child entries. A „root entry“ has got the ParentId "urn:uuid:00000000-0000-0000-0000-000000000000" or it is null. This information is sufficient to write some extension methods on DataFeed and DataEntry for getting hierarchical information. Thus I’m starting to make a little class library, which I will further work on and extend it. First I’ve got a little class named „MeshConstants„. There resides the ParentId for a root data entry:

public static class MeshConstants
{
    public const string RootDataEntryId = "urn:uuid:00000000-0000-0000-0000-000000000000";
}

With this it’s easy to extend DataFeed with a method GetRootDataEntries(), which delivers only the data entries on the top level of the hierarchy:

public static ICollection<DataEntry> GetRootDataEntries(this DataFeed feed)
{
    return (from entry in feed.DataEntries.Entries
            where entry.IsLoaded && entry.IsRootEntry()
            select entry).ToList();
}

This method accesses IsRootEntry() of DataEntry, which is an extension method, too and indicates, if a data entry is on the root level (has no parent) or not:

public static bool IsRootEntry(this DataEntry entry)
{
    if (String.IsNullOrEmpty(entry.Resource.ParentId))
        return true;

    return entry.Resource.ParentId.Equals(MeshConstants.RootDataEntryId);
}

Another extension method for DataEntry gives us the child entries in return:

public static ICollection<DataEntry> GetChildEntries(this DataEntry entry)
{
    return (from child in entry.GetDataFeed().DataEntries.Entries
            where child.Resource.ParentId == entry.Resource.Id
            select child).ToList();
}

This makes use of the method GetDataFeed(), which is needed for getting the data feed, this data entry is associated to. Unfortunately, the .NET libraries of the Live Framework CTP don’t come along with this possibility innately:

public static DataFeed GetDataFeed(this DataEntry entry)
{
    return (from feed in
                (from meshobj in entry.LiveOperatingEnvironment.Mesh.MeshObjects.Entries
                 select meshobj.DataFeeds.Entries).Aggregate((fl1, fl2) => fl1.Union(fl2))
                 where feed.DataEntries.Entries.Contains(entry)
            select feed).Single();
}

Example: traversing the hierarchy

Now we’ve got all together for traversing a hierarchy of data entries recursively. We just need a recursive method, which executes the wanted action for a data entry and then recursively calls itself for all child entries. The following example method builds up a WinForms TreeView structure by adding TreeNode elements recursively:

private void addTreeNodesForChildDataEntries(DataEntry parentEntry, TreeNode parentNode)
{
    foreach (var childEntry in parentEntry.GetChildEntries())
    {
        var childNode = new TreeNode(childEntry.Resource.Title + ": " + childEntry.Resource.Type);
        parentNode.Nodes.Add(childNode);
        addTreeNodesForChildDataEntries(childEntry, childNode);
    }
}

The result is shown below exemplarily:

Live Framework - Recursing TreeView example

Types of LiveItem elements

The resources of MeshObject, DataFeed and DataEntry have an associated Type property, over which you can distinguish different types of objects. Furthermore, Type is a string and thus allows you to define your own application-specific object types. But the Live Framework comes with some standard types by default, where the most important are:

MeshObject.Type:

  • "LiveMeshFolder": Top-level folder, which can contain further (data entry) folders and files.
  • "ApplicationInstance": Instance of an application, which has been installed through the Live Application Catalogue.

DataFeed.Type:

  • "LiveMeshFiles": Indicates the feed as container for file and folder data entries.

DataEntry.Type:

  • "Folder": Data entry is a folder, which can contain further data entries.
  • "File": Data entry is a file, which may contain your data.

Based on that information (and the extension methods above), I’ve written some more extension methods on the several classes to filter the child elements accordingly:

public static class MeshObjectTypes
{
    public const string LiveMeshFolder = "LiveMeshFolder";
    public const string ApplicationInstance = "ApplicationInstance";
}

public static class DataFeedTypes
{
    public const string LiveMeshFiles = "LiveMeshFiles";
}

public static class DataEntryTypes
{
    public static string File = "File";
    public static string Folder = "Folder";
}

public static class MeshExtensions
{
    public static ICollection<MeshObject> GetApplicationInstanceMeshObjects(this Mesh mesh)
    {
        return (from meshobj in mesh.MeshObjects.Entries
                where meshobj.Resource.Type == MeshObjectTypes.ApplicationInstance
                select meshobj).ToList();
    }

    public static ICollection<MeshObject> GetFolderMeshObjects(this Mesh mesh)
    {
        return (from meshobj in mesh.MeshObjects.Entries
                where meshobj.Resource.Type == MeshObjectTypes.LiveMeshFolder
                select meshobj).ToList();
    }
}

public static class MeshObjectExtensions
{
    public static ICollection<DataFeed> GetFilesChildFeeds(this MeshObject meshobj)
    {
        return (from feed in meshobj.DataFeeds.Entries
                where feed.Resource.Type == DataFeedTypes.LiveMeshFiles
                select feed).ToList();
    }
}

public static class DataFeedExtensions
{
    public static ICollection<DataEntry> GetFileDataEntries(this DataFeed feed)
    {
        return feed.GetFileDataEntries(false);
    }

    public static ICollection<DataEntry> GetFolderDataEntries(this DataFeed feed)
    {
        return feed.GetFolderDataEntries(false);
    }

    public static ICollection<DataEntry> GetFileDataEntries(this DataFeed feed, bool onlyRootEntries)
    {
        var entries = onlyRootEntries ? feed.GetRootDataEntries() : feed.DataEntries.Entries;
        return (from entry in entries
                where entry.Resource.Type == DataEntryTypes.File
                select entry).ToList();
    }

    public static ICollection<DataEntry> GetFolderDataEntries(this DataFeed feed, bool onlyRootEntries)
    {
        var entries = onlyRootEntries ? feed.GetRootDataEntries() : feed.DataEntries.Entries;
        return (from entry in entries
                where entry.Resource.Type == DataEntryTypes.Folder
                select entry).ToList();
    }
}

public static class DataEntryExtensions
{
    public static ICollection<DataEntry> GetFileChildEntries(this DataEntry entry)
    {
        return (from child in entry.GetChildEntries()
                where child.Resource.Type == DataEntryTypes.File
                select child).ToList();
    }

    public static ICollection<DataEntry> GetFolderChildEntries(this DataEntry entry)
    {
        return (from child in entry.GetChildEntries()
                where child.Resource.Type == DataEntryTypes.Folder
                select child).ToList();
    }
}

kick it on DotNetKicks.com

Live Framework CTP #4 – .NET: LOE and data basics

Instead of creating new Silverlight applications, which run in your mesh and use the data, you can furthermore mesh-enable your existing .NET applications or create new mesh-enabled .NET applications from scratch. That’s pretty easy and in the following post I will show you some basics…

The Live Operating Environment (LOE)

First there is the Live Operating Environment, being the center point of all your operations to the mesh. With an object of type LiveOperatingEnvironment you can connect to your online mesh or to your local mesh storage sync or async and perform any operation you want. But that’s just the developer’s point of view. In fact, the LOE (every instance of it) is an agent component, responsible for providing an efficient cache and for background synchronization of data on your device to other devices (other instances of the LOE on those devices) in your mesh, including the „special“ LOE in the cloud. Running an LOE means exposing data through a RESTful interface at port 2048 of your machine – one could check the presence of this and either connect locally or to the cloud.

Connecting to your online/cloud LOE means that you have to provide your credentials on connect, whereas you can connect locally without those. I like to work on my local storage, it’s fast and safe. But there are some limitations (at the moment?) there. Due to the lack of file synchronization, files as data entries are not available from the local storage, so you have to connect to your online LOE instead. Furthermore you only get your local device in the Devices collection of your LOE and it’s not possible to have a look at your contacts and profiles for instance. What I expected first or want to have for the „final“ version of the Live Framework: just one connection method, which takes local data if it’s available and instead connects to the cloud LOE. It should be no problem, because the various LOEs (loal, cloud) are taking responsibility over synchronization… or have I forgotten to consider something?

Well, let’s take a look to connecting to your (online) LOE. Just create an instance of LiveOperatingEnvironment and connect via the Connect() method (local LOE: use ConnectLocally() instead). You have to pass your credentials as a parameter, which could come from a secure source or from user input:

var creds = new NetworkCredential("username", "password", "https://user-ctp.windows.net");
var loe = new LiveOperatingEnvironment();

loe.Connect(creds);

https://user-ctp.windows.net is the fixed base URI when connecting to your cloud LOE. After you’ve been connected, you get access to your mesh items (shown before) and can start meshing 🙂

Mesh Objects, Data Feeds and Data Entries

A mesh object is a container for concrete data in your mesh. There are several types of mesh objects and you are allowed to create your own application specific types, which your applications can work with. Mesh objects can be files, folders, applications, custom objects etc.. You have access to the mesh objects via loe.Mesh.MeshObjects.Entries and have the possibililty to easily iterate over them in this way.

Every mesh object consists of DataFeeds, Members, Mappings and News, as stated before. Interesting at this point are the data feeds. Those are further containers for the real data entries. Why this abstraction? Over data feeds you can group your data together, separating logically distinct data. Every DataFeed object finally contains a DataEntries collection, which gives you access to the underlying data and information about that. Note: there is no obvious possibility to store hierarchical data entries at the moment. There is one level of data entries and a data entry can’t contain other data entries. So that’s a drawback at this point and I don’t like/understand it much. The solution for that is: every data entry contains a parent ID and over that you can identify top level data entries and those, who are child entries of another data entry. But that’s not a good solution, isn’t it? Hopefully there will be done some work on that…

Well, a nice little .NET console application would be to show us the titles of all mesh objects, of their data feeds and data entries in there. That’s no problem and leads to the following little program:

var creds = new NetworkCredential("username", "password", "https://user-ctp.windows.net");
var loe = new LiveOperatingEnvironment();
loe.Connect(creds);
if (loe.IsRunning())
{
    foreach (var meshobj in loe.Mesh.MeshObjects.Entries)
    {
        Console.WriteLine("- " + meshobj.Resource.Title);
        foreach (var feed in meshobj.DataFeeds.Entries)
        {
            Console.WriteLine("  + " + feed.Resource.Title);
            foreach (var entry in feed.DataEntries.Entries)
                Console.WriteLine("    * " + entry.Resource.Title);
        }
    }
}
Console.ReadLine();

Create, Update, Delete

The creation, update and delete of all the three entities MeshObject, DataFeed and DataEntry is made really easy. Just call the Add() and Remove() methods of the particular collections. The rest is done automatically by the Live Framework. The update process isn’t problematic, too. Just change your entity and then make sure to call the Update() method of this entity. Because everything in your Live Operating Environment has LiveItem as base type, you have an integrated and consistent CRUD process.

Little example

The following screenshot shows a little WinForms application, that connects to my mesh and over which I can perform the CRUD process on my mesh entities. Further on I can navigate through my mesh and if I got images as data entries, those are downloaded automatically as media resource stream and then shown up at the picture box on the right. In the screen below is shown the (IKEA-powered 😉 ) couch corner of my little apartment…

Live Framework .NET WinForms example application

In upcoming blog posts I want to show you more information about handling data entries, media resources and hierarchical data. So stay tuned 🙂

kick it on DotNetKicks.com

Live Framework CTP #3 – .NET: the developer’s Resource Model

There seems to be a lack of information on the web about the Live Framework Resource Model from a developer’s point of view, that means how can I address my mesh objects and more from my .NET code. Some Blog-Entries describe it more from a user’s standpoint respectively describe what is unveiled through the web services of the Live Operating Environment, but as .NET developer with the LiveFx libraries at hand that’s not interesting me much. Thus I want to briefly describe the resource/data model which you’re programming against in .NET (it has some similarities to the real class diagram) through the following article. Later on, in other posts I will go in depth on some of them.

The following diagram shows many (while not all) aspects of what you as developer should be worried about when juggling with Live Framework objects:

Live Framework Resource Model

First things first: every collection shown above is a LiveItemCollection<TMeshItem, TResource>, where TMeshItem is of type MeshItem and TResource is of type Resource. Normally you get data out of the Resource, which can be extracted from the LiveItem via YourLiveItem.Resource.

Now I want to shortly describe the individual components.

LOE: the Live Operating Environment is the root of all functionality. Here you can connect to your Mesh and get all the information you need (In fact it’s much more than that, but this should be deferred at the moment).

  • Contacts: Collection, which holds your contacts. One contact can contain some profiles and has many relevant contact data (Name, adresses, job title, profession etc.) connected to it.
  • Mesh: Represents your whole mesh and the data, that it contains.
  • Profiles: Respresents your personal profiles. The following kinds of profiles are available: General, AboutYou, ContactInfo, WorkInfo, Interests. Those profiles come from your Windows Live account, so Windows Live is basically integrated with some functions at the moment. I’m sure that there will be more interaction and features including Mesh and Windows Live in the future.

Mesh:

  • Devices: Collection, that represents the different kinds of devices belonging to your mesh. Those are the same devices that are shown on the device ring in your browser. From a device object you can gather information like the online status, if it’s a local device or if it has an active remote connection.
  • MeshObjects: Everything, which can contain data (data feeds) in your mesh. This can be folders (Type: LiveMeshFolder) and applications (Type: ApplicationInstance) for example.
  • News: Collection of NewsItem objects, which represent global news in the mesh. There are several kinds of existing News types: LiveMesh.FileAdd, FolderAdd, MemberAdd, AppInstanceCreate, AppInstanceMemberAdd, UserMessagePost and more. But you’re not limited by these, because you can create news of your own type…

MeshObjects:

  • DataFeeds: Collection of container items for data, that is included in the mesh object. Every data feed can have many data entries.
  • Mappings: Collection, that contains mapping objects. Those indicate the devices this mesh object is mapped to.
  • Members: Individuals, who have permission to this mesh object. There are several role type for mesh object members: Full, Author, Reader, Writer. With those the core Live services and your applications can handle access to mesh objects.
  • News: Every mesh object can have several news, that are related to this object. As the global news, this is a LiveItemCollection of NewsItem objects.

DataFeeds:

  • DataEntries: Data entries are everything that contains data in a data feed. This can be files or folders or user-specific data. A data entry can contain a media resource, with which a file (image, video, audio, word document, …) can be viewed and converted automatically.

These are just some first thoughts and introductionary information about the resource model from a developer’s view. As said before, I will blog later on specific topics of that, going more in depth…

kick it on DotNetKicks.com

Live Framework CTP #2 – Silverlight: Hello Mesh

I recently created my first little mesh applications. And yeah, I like it! One of those was a simple „Hello Mesh“ Silverlight application, only to get familiar with the mesh application creation and deployment process.

Fist I created a new „Silverlight Mesh-enabled Web Application“, which can be chosen through the new „Live Framework“ project type, (comes with the Live Framework Tools for Visual Studio).

New Live Framework Project Type
New Live Framework Project Type
This results in the following project structure:
Silverlight Mesh-enabled Web Application project structure

There is a main application project „MeshApp1“, whose icon indicates that it’s mesh-enabled. Furthermore it contains a page that is hosting the Silverlight application „MeshApp1Silverlight“. I’ve heard that there are some problems, if you want to adopt this project structure to your custom needs. Some people seem to have problems when adding new references and projects, making the Silverlight application not work on a machine’s desktop. I’m sure that Microsoft is working on that, don’t forget we just have a CTP at the moment 😉

In Blend I’m layouting „Hello Mesh“ a little bit, so that my Mesh in the cloud is getting happy when it sees my application. Back in Visual Studio and ready to run, I make a thing which I call F5 deployment, regarding the effect of pressing the F5 key in my solution. So what’s going on? When you press F5 the first time, a dialog is popping up that is showing you some information about deploying your app:

Deployment dialog for a mesh-enabled web application

At present you have to make some handwork on this. With the Live Framework you can create up to 25 projects at the moment, this should be enough for some playground experiences. The dialog is showing you the way: you have to go to your Azure developer center and create a new project. In return you get an application self-link (the URI for the application), which the dialog wants from you. With this, Visual Studio knows where to deploy the application automatically, when you press F5 the next time. My opinion on this is that this kind of handwork could be made a little smarter or more automatic, but remember: you have to make it only once, so it is quite ok for me. 

What I think about this: that is how cloud application development and deployment should look like! Easy development with respect to your existing skills and easy deployment of your applications. Furthermore, with the application’s self-link, Visual Studio is able to debug your applications in the cloud. That’s great! No competitor of Microsoft gives you these possibilities and in my opinion it’s making a big difference and will contribute much to the success of Microsoft’s cloud strategy. Attracting developers is the core of all.

Aehrm, where have I been? Oh yeah… well… when you press F5, your Silverlight application will start in the cloud. The Live Desktop will open up and your Silverlight application will get a shortcut on it. It starts on your Live desktop, showing the overwhelming „Hello Mesh“ result:

Silverlight Mesh Application on the Live Desktop

If you run the „Live Framework Client“, this app automatically creates a shortcut on your machine’s desktop to the MeshApp1 Silverlight application. And in the background, it automatically synchronizes the application to your machine. Now try the following (it works!): disconnect from the Internet, click on the shortcut at your desktop and the application runs! Without connection, on your desktop. This really impresses me and I will try some more complex scenarios later on…  Here’s the local desktop result:

Silverlight Mesh-enabled Web Application on the local desktop

First conclusion: I like/love my first experiences with the Live Framework and that I can use my existing development skills. The deployment process is intuitive and easy and brings my expectations to life. I will go on with some more topics during the next days and weeks.

kick it on DotNetKicks.com

Live Framework CTP #1: Start!

The last two days I started playing around with the Live Framework CTP, where I was lucky to get a token from. I will write about my experiences in a series of postings in this place, so stay tuned. I encountered with some first issues and want to write about those in this posting.

Installation

After redeeming my Live Framework CTP token, I was able to download the following packages:

  • Live Framework Client: similary to the „normal user“ Live Mesh client, the Live Framework client runs in the background and allow synchronisation. In difference to the Live Mesh client it’s limited in functionality, as you will see later on. Note: the Live Framework Client is not needed for you as a developer to program against the Live Services, it’s just for background synchronisation.
  • Live Framework SDK: The Software Development Kit for the Live Framework. There is only a zip archive, no installation package. You have to copy the included folder into „C:/Program Files/Microsoft SDKs/“  by yourself. The SDK contains a resource browser tool, application samples, some documentation and libraries for .NET, Silverlight and Javascript.
  • Live Framework Tools for VS: This is an installation package which gives you a new project type „Live Framework“ when creating a project in Visual Studio, as shown below. There you can choose between „Mesh-enabled Web Application“ (allows you to create a Web App using the Live Framework Javascript library) and „Silverlight Mesh-enabled Web Application“, if you got the Silverlight Tools installed. Additionally it allows you to deploy your mesh application automatically in your mesh when running the app (I call it F5 deployment and like it very much – that’s how cloud should look from a developer’s point of view). Independently you can manually create mesh-enabled console/WPF/WinForms applications by adding the required libraries as references to your project. Thus you can easily add some mesh-functionality to your given applications.

That’s it. Installation worked fine except for the Live Framework Client (see below).

New Live Framework Project Type
New Live Framework Project Type

Developer Sandbox

With your Live Framework token you get a completely new Mesh in https://developer.mesh-ctp.com/. That means you can not use your existing „user“ Mesh from https://www.mesh.com/. You have to add devices again to your developer Mesh and it has the same 5GB storage (at the moment) and device ring/Live Desktop as your user mesh. In difference you can add applications to your developer mesh and this makes a big and even great difference.

Applications

At the moment there is no possibility to run applications in your user mesh. The developer mesh allows this. Some days before I shortly wrote (in German) about the Meshpack, which comes with 4 little Silverlight applications. The developer mesh allows you to include those 4 applications in your mesh with your Live Framework token at hand. The „Apps“ tab of your developer mesh will show those apps and allows you to create new instances of each one, which will appear on your Live Desktop and can be run from there. I’m waiting in suspense to see which applications will be available in the future through the public application catalogue, how they can be included in Windows Live and how you can share applications and there data with your friends!

The meshpack installed in the developer mesh
The meshpack installed in the developer mesh

Live Framework Client

The Live Framework and Live Mesh Clients

The „Live Framework Client“ is the developer mesh’s pendant to the „Live Mesh Client“ a normal user’s mesh comes with. The Client can be installed and then runs in the background. A taskbar icon will show you that you’re connected with your developer mesh and gives you recent news of your mesh.

There’s a really annoying issue with the Live Framework Client: if you have the Live Mesh client installed, you cannot install the Live Framework client! This frustrated me because I want to use the Live Framework, but at the same time I don’t want to miss the Live Mesh functionality on my machines.

Live Mesh and Live Framework client running side by sideBut I found a solution/workaround for this: you can uninstall the Live Mesh client and then you’re able to install the Live Framework client. After that install the Live Mesh client again and then you will not encounter any problems. I don’t know why Microsoft doesn’t allow both applications to run at the same time and I don’t know if there could be any problems with that. Until now I don’t have troubles with both applications and there synchronization functionalities.

In comparison to Live Mesh, the Live Framework client has some limitations in functionality. There is currently no ability to synchronize folders to your machine and you can’t connect remotely to other machines. Furthermore you can’t get online/offline information for your machines. At first look these are really annoying limitations, but at the second look it is no big problem for you as developer, who wants to explore the functionality of the Live Framework, not of the client.

The really great thing at the Live Framework Client is: you can synchronize applications between your mesh and your machines! From a developer’s point of view, applications in your mesh are just simple mesh objects, like mesh folders, mesh files and so on. This gives you a nice and consistent view of everything in your mesh. Applications can have data feeds, that means data which they contain. They have all the nice things other mesh objects have, too: news, members, feeds, mappings, …   and you can iterate through them programmatically, which will be shown in one of the next posts. So what means application synchronization? First when you include or deploy a Silverlight application into your mesh, you will automatically get a shortcut on your machine’s desktop! Thus you can start applications from your Live Desktop on the browser or directly from your desktop – it doesn’t matter. And with synchronization you’ll get all the data of the application (this means all data of the mesh object which is represented by your application). You can work offline with this data and if you come online again, this data will synchronize automatically with your mesh. Great stuff, isn’t it? I will give an in-depth look on that in a later blog entry…

When taking the meshpack as an example, there you’ve got the corkboard application. If you create a new instance of that in your mesh, you’ll get a shortcut on your Live Desktop and can start the app from there as shown below:

The corkboard application running on the Live desktop
The corkboard application running on the Live desktop

At the same time the Live Framework client notices the new application, synchronizes it with your machines and makes a shortcut on your desktop. From there you can start the application, which gives you nearly the same view as on your Live Desktop:

The corkboard application running locally on the user PC's desktop
The corkboard application running locally on the user PC's desktop

Live Mesh? Just an application!

When I first heard of and used the Live Mesh, I thought and spoke of Live Mesh all the time. But then I reconsidered the whole thing and found out the players behind the scenes. Is it Live Mesh we should speak about as developers? No, it’s not! Live Mesh is nothing but an application, a frontend of the real Mesh. In this mesh you have some nice things like devices, profiles, contacts, mesh objects (data, applications, …)  etc., which are populated via a restful web interface. Live Mesh uses this interface for displaying the device ring and Live desktop in your browser and for the features of the Live Mesh client (synchronization, …). The functionality of the Mesh itself is enabled by the Live Services as part of the service layer of Windows Azure. And with the Live Framework, you as developer are able to code against these Live Services and use all the functionality and data which are offered through Mesh and the Live Services. Thus you are able to create applications similar to Live Mesh or something really new. As your future killer apps, Live Mesh is only an end-user-friendly application build on the Live Services basement.

kick it on DotNetKicks.com

Guys, it’s Christmas (for me) – let’s start meshing!

Wow, that’s so really really great. I’ve written about my pains (German) while waiting for the Live Framework CTP Token before, but no the pains have ended! No, I did NOT get a token while poping out of the waiting list. I’m such a lucky man… Here’s the story: yesterday by „accident“ I was on a web page of a Live Framework blogger and by „accident“ I wrote her an e-mail, if she wouldn’t have a token for me. And in response:

You are lucky, my last token was requested through the blog but the person never responded back. [Here you have it]

Guys, I’m soooo happy! Finally I can now get experienced with the Live Framework, write my meshified applications and blog about it. What a beautiful day… it’s Christmas for me (only better ^^) 🙂

Silverlight toolkit december released

The first release of the SIlverlight toolkit a few weeks ago brought some interesting new controls, charting and theming to Silverlight. Now they enjoy us with the december release of the toolkit.

Changes in short:

  • AutoCompleteBox and NumericUpDown have made it to the stable branch
  • Charting has been improved and is now easier for you to code against (thanks!!!)
  • better designer integration
  • 3 new themes (Bureau black, Bureau blue, Whistler blue)

I love those guys and their work on the toolkit and I’m interested to see this project moving forward.

http://www.codeplex.com/Silverlight

ASP.NET MVC Tip: Got an Ajax Request?

Job-related I’m diving into this ASP.NET MVC stuff currently and will give you at this point some posts on that in the nearer future. Just for now: I like ASP.NET MVC and how MS implemented the core concepts. It’s clean, testable, flexible and extensible. Many things have changed since beyond standard ASP.NET…

Currently I’m becoming inspired by the Ajax Helpers, which ship with ASP.NET MVC. With Ajax.BeginForm(), Ajax.ActionLink() and Ajax.RouteLink() there currently (ASP.NET MVC Beta 1) exist three extension methods, which one can use after integrating the Microsoft Ajax script libraries in his page and which provide basic Ajax functionality.

At the moment I’m using Ajax.ActionLink() in my project to reload parts of my page, if the user clicks on a link. Especially I’m reloading data asynchronously, which the user changed through his click. That’s working pretty perfect for me, additionally I can serve a Confirm-Message via the AjaxOption „Confirm„, which is presented to the user before executing an action and over which the user can canel an action, too.

There’s one problem for me in this case: with the ActionLink ASP.NET MVC calls an Controller-Action. That’s happening via a special URL, which is mapped by the ASP.NET MVC routing system to an action. This action delivers with PartialView() the data (View), which are injected in the existing page with the aid of Ajax. The problem is: the user can pass this URL directly in his browser too and then he gets only those partial data in response, but not the whole page as in the case when he’s using the Ajax-ActionLink.

Some googling and testing yielded two ways for resolving this problem:

1st) One action with discrimination of the request type

First of all it’s possible to create an action, which can be invoked through both the Ajax ActionLink and the user through an URL in his browser. After including the namespace „System.Web.Mvc.Ajax“ one can use the extension method „Request.IsMvcAjaxRequest()“ in his controller action, with which it’s possible to check if the current request is coming from an ASP.NET MVC Ajax helper. Accordingly you are able to return the PartialView (on an Ajax request) or the complete view of your data (in case there’s no Ajax request). This is looking roughly as follows:

using System.Web.Mvc;
using System.Web.Mvc.Ajax;
...

namespace MyNamespace
{
    public class MyController : Controller 
    {
        ...
        public ActionResult MyAction(...) 
        {
            if(Request.IsMvcAjaxRequest()) 
            {
                ...
                return PartialView("MyPartialView", myPartialModel);
            } 
            else 
            {
                ...
                return View("MyCompleteView", myCompleteModel);
            }
        }
    }
}

Is this solution pretty? Well… Kevin Hoffman is criticizing the additional discrimination of the request type in the controller. Especially it’s coming out that Kevin sees the MVC principle violated, because this discrimination is going beyond the responsibility of a contoller (the following quote refers to an older ASP.NET MVC release, where there was an AjaxController with an IsAjaxRequest property):

MVC is all about proper separation of concerns. There’s one line of code in the sample that I think is violating that, and that’s the IsAjaxRequest property. This all smacks of someone attempting to make the MVC framework feel more like the old Postback world and quite frankly, the old postback world can eat my shorts. The controller, IMHO, is just a controller. It should not ever have to determine if it is rendering Ajax or rendering Regular. Ajax or regular HTML is a view decision not a controller decision. The job of the controller is to fetch the appropriate data required for rendering a view, and then pick the view to render.

Strongly taken I agree with Kevin from the architectural point of view. The view should be responsible to decide how some data is displayed, the controller should only deliver this data. On the other hand side my own individual opinion is that the controller should be able to decide, to which view it’s sending the data it fetches. Many controllers are doing so… e.g. they are calling an error page instead of the actual view if something goes wrong or they are redirecting to other views depending on the count of the received data. The only thing I’m worried about in this case is that the decision „Ajax-call or not“ is design-oriented and does not depend on data, which is fetched in the controller action itself, but which depends on the initial request. Though I’m not worried much about this, I’ve worked out another solution, which I’m coming up with in the following section…

2nd) Two actions with attributation

If you want to avoid a discrimination by „IsMvcAjaxRequest()„, you have to implement a second action. A first action „MyAction“ can then be called by the user via his browser and will return the complete view, where the second action -named e.g. „MyActionAjax„- could return a partial view, which is relevant for the Ajax request. This is looking as follows:

using System.Web.Mvc;
...

namespace MyNamespace 
{
    public class MyController : Controller 
    {
        ...
        public ActionResult MyAction(...) 
        {
            return View("MyCompleteView", myCompleteModel);
        }

        public ActionResult MyActionAjax(...) 
        {
            return PartialView("MyPartialView", myPartialModel);
        }
    }
}

Please identify that the basic problem still persists: the user can call „MyActionAjax“ via his browser. And here comes the trick: we’ll attribute „MyActionAjax()„, thus refusing the access. I’ve written a filter attribute, which is dealing with this:

using System.Web.Mvc;
...

namespace SDX.xMedia.mvc.Presentation.Common
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class MvcAsyncPostAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext != null && filterContext.HttpContext != null)
            {
                if (!IsMvcAsyncPost(filterContext.HttpContext.Request))
                    filterContext.Cancel = true;
            }
        }

        private bool IsMvcAsyncPost(HttpRequestBase request)
        {
            if (request == null)
                return false;

            return request["__MVCASYNCPOST"] == "true";
        }
    }
}

In this case I’m walking by foot. The Ajax helpers from ASP.NET MVC are setting the request parameter „__MVCASYNCPOST“ when performing an Ajax request. Further the extension method „Request.IsMvcAjaxRequest()“ is implemented in a way, which is only querying this value. Here is the current implementation from the ASP.NET MVC project:

public static bool IsMvcAjaxRequest(this HttpRequestBase request)
{
    if (request == null)
    {
        throw new ArgumentNullException("request");
    }
    return (request["__MVCASYNCPOST"] == "true");
}

Thus of course I can use this method for my request:

using System.Web.Mvc;
using System.Web.Mvc.Ajax;
...

namespace SDX.xMedia.mvc.Presentation.Common
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class MvcAsyncPostAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext != null && filterContext.HttpContext != null && filterContext.HttpContext.Request != null)
            {
                if (!filterContext.HttpContext.Request.IsMvcAjaxRequest())
                    filterContext.Cancel = true;
            }
        }
    }
}

By the way: IAuthorizationFilter has been implemented, because only in this way I was able to cancel the execution of the action in the first place ( filterContext.Cancel = true; ). Now with this attribute it’s possible to mark the „Ajax-only“ action and this way to prohibit the access through the browser:

using System.Web.Mvc;
...

namespace MyNamespace 
{
    public class MyController : Controller
    {
        ...
        public ActionResult MyAction(...)
        {
            return View("MyCompleteView", myCompleteModel);
        }

        [MvcAsyncPost]
        public ActionResult MyActionAjax(...)
        {
            return PartialView("MyPartialView", myPartialModel);
        }
    }
}

Now which way is prettier? Architecturally I like the second variant with regard to the separation of concerns principle which lets the controller do the stuff it should do. But there is one unaesthetic point in my eyes: the Ajax ActionLink is referencing to the action „MyActionAjax()“ and this link is delivered to the user by his browser. The user could be confused when he wants to share this link with one of his friends and has no direct access to the controller action, which stands behind this url. Thus from a user’s point of view the first solution makes more sense, but there has to be a trade-off as the case arises and I’m agog about your thoughts.

Update for the second solution:

My problem with the second solution was the action-link, which is pointing to MyActionAjax() and thus provided to the user. Now I’ve worked out a quick and dirty work-around for that (and guess what: no I don’t like it). I’m setting up my own RouteHandler in the following way:

class AjaxRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        if (requestContext.HttpContext.Request.IsMvcAjaxRequest())
            requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"] + "Ajax";

        return base.GetHttpHandler(requestContext);
    }
}

Now you can set up your routes with this route handler:

RouteTable.Routes.Add(
    new Route("{Controller}/{Action}/{id}",
    new RouteValueDictionary(new { Controller = "MyController", id = (int?)null }),
    new AjaxRouteHandler()));

What’s done: if there is no Ajax request, then the „normal“ action will be invoked (e.g. „MyAction“). On an Ajax-request instead there will be called the action „MyActionAjax“ automatically. Note that the programmer has to be responsible for the availability of this action pair. The benefit of that: you can provide „MyAction“ in your Ajax-ActionLink or call it via your browser and share the url with your friends. The route handler decides whether to invoke MyAction or MyActionAjax. Thus the responsibility for deciding if we’ve got an Ajax request comes out from the controller into the route handler. Please remember that I don’t have anything against having this piece of code in my controller, I’m just here to show some other way for solving this problem…

kick it on DotNetKicks.com

XAML Power Toys

Heute beim Stöbern entdeckt, das dürfte einige von euch (speziell die Silverlight/WPF-XAML-Jongleure ^^) sicher interessieren 🙂

XAML Power Toys is a Visual Studio 2008 SP1 Multi-AppDomain Add-In that empowers WPF & Silverlight developers while working in the XAML editor.  Its Line of Business form generation tools, Grid tools,  DataGrid and ListView generation really shorten the XAML page layout time.

XAML Power Toys generates .NET 3.5 SP1 WPF compliant XAML and Silverlight 2 compliant XAML.

It’s accessed through commands in the XAML editor context menu and the Solution Explorer item context menu.

Link: http://karlshifflett.wordpress.com/xaml-power-toys/

Architektur erlernen

Golo Roden hat einen netten Blog-Eintrag erstellt, in dem er beschreibt, wie man sich dem Thema Software-Architekturen nähern kann. Meiner Meinung nach hat Golo hier einige Dinge angesprochen, die für den Einstieg ganz nett sind und die Einstiegshürde nehmen. Auch bei mir stellte (und stellt sich immer wieder) die Frage, wie ich zu einem besseren (oder überhaupt einem ;-)) Architekten werden kann. Meiner Meinung nach sind Leute sehr hilfreich, die einfach einen breiten Begriffsschatz zu dem Thema haben. Mit der Zeit schnappt man von diesen Leuten Begriffe auf, die mit dem Thema Architektur zu tun haben und durchsucht dann das Internet für weitere Informationen zu den jeweiligen Themen. Doch der beste Lehrmeister ist immernoch die Praxis. Man muss einfach selbst Erfahrungen sammeln (und das über Jahre hinweg), um feststellen zu können, welche Dinge funktionieren, welche nicht und warum sie das tun bzw. nicht tun. Dieses Hinterfragen ist essentiell und unerlässlich dafür, seine Lösung später auch vor anderen verteidigen zu können.

Zu guter Letzt noch ein Tipp: beim Thema Architektur sollte man 1.) nie auf der eigenen Meinung verharren und vor allem 2.) sein Design der zu erstellenden Anwendung anpassen. Bei 1.) sollte man begründen können, warum eine Architektur schlecht ist und das mit Gründen, die für das aktuelle Projekt auch relevant sind. Jedes Projekt ist anders und besitzt andere Rahmenbedingungen, die Frage nach einer „guten“ Architektur ist daher sehr dynamisch und individuell verschieden! Auch ich bin hier gerade in einem Lernvorgang, umso wichtiger ist es mir diese Erfahrung als Tipp weiterzugeben. Zu 2.) ist zu sagen, dass man das KISS-Prinzip beherzigen sollte: keep it solid and simple! Eine abgefahrene Architektur macht nur dann Sinn, wenn das Projekt sie auch erfordert. Seine Kreativität ausleben zu können ist kein Grund dafür, wilde Architekturspielereien durchzuführen, z.B. durch den Einsatz von Mocking- oder Dependency-Injection-Frameworks. Austauschbarkeit von Komponenten wie dem Datenzugriff ist beispielsweise so eine Spielerei, die nur in wenigen Projekten auch sinnvoll ist. Erst wenn die fachliche Anforderung es konkret erfordert, sollte ein Aspekt in den Entwurf des Architekturdesigns mit einfließen. Man sollte sich immer wieder selber fragen: benötige ich es überhaupt, wenn ja aus welchem Grund und geht es vielleicht auch anders/einfacher? Hilfreich ist auch die Vorstellung, dass man seine Lösung und die einzelnen Teile bei seinem Auftraggeber verteidigen muss. Wenn hier als Argument nur übrigbleibt: „ja das ist jetzt schön austauschbar“, die Anforderungen es aber nicht erfordern, spätestens dann sollte man sich fragen, ob man nicht etwas falsch macht…

Wie gesagt, ich selbst sehe mich perspektivisch als Architekt und finde das ganze Thema sehr spannend, stehe aber 2 Monate nach meinem Studiumsabschluss selber noch ziemlich am Anfang 🙂