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

English… I’m here!

Yes, I will change my blog language to English from now on due to more than one reason. On the one hand side I want/have to practice my English skills. I’m familiar in reading English, but not very familiar in writing, yet. I had an English advanced course at school, but this is years ago…  Please forgive me some cumbersome linguistic constructions, my English is not perfect, but I will try hard to improve my skills.  On the other hand side, most technical blogging is in English and while attracting more foreign users, I want to give them a language they can understand (I know, German can be frightening sometimes 😉 ). Comments, anyone?

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 🙂

Bitte lasst meine Qualen enden!

Bitte Microsoft, habt Erbarmen mit uns! Bitte lasst die endlose Zeit der Warteliste vorübergehen und uns das Live Framework downloaden! Bitte lasst uns endlich gegen dieses Framework programmieren, lasst uns darüber bloggen, lasst uns darüber austauschen und unsere Kreativität darin ausleben. Bitte lasst die Qualen endlich enden.

Einen Monat warte ich nun schon auf einen Key für das Herunterladen des Live Frameworks, doch leider steht eine Freigabe noch immer aus. Und das bedeutet: anstatt weiter darüber zu bloggen, Tutorials zu schreiben und meine „Mesh-enabled applications“ damit zu entwickeln, drehe ich hier zu Hause Däumchen und hoffe auf ein vorzeitiges Weihnachtsgeschenk von Microsoft-Seite aus. Die Hoffnung stirbt zuletzt 😉

Dariusz Parys hatte heute für kurze Zeit 2 Keys für das Live Framework zu vergeben, die natürlich sofort weg waren. Das macht die Sache nur noch unerträglicher für mich, wann hat das Warten endlich ein Ende? Was mich zur nächsten Frage führt, warum überhaupt eine Warteliste existiert. Meine Vermutung sind derzeit mangelnde Ressourcen im Backend, die ansonsten vielleicht nicht ausreichen würden, wenn Tausende von Entwicklern ihre Programme auf ihren Meshs laufen lassen. Andere Ideen?

Silverlight Wünsch-Dir-Was

Wer Microsoft schon immermal über Silverlight die Meinung geigen wollte, hat jetzt Gelegenheit dazu. Microsoft hat eine Umfrage zu Silverlight gestartet, wo jeder Entwickler darüber abstimmen kann, was ihm an Silverlight gut gefällt und was noch bitter aufstößt.

Zusätzlich ist es möglich, Wünsche für das kommende Silverlight 3 zu äußern.

http://deploy.ztelligence.com/start/survey/survey_taking.jsp?PIN=13AQC8W8EAHZP

Evolution eines Entwicklers

Jeremy Miller hat in seinem Blog einen wirklich interessanten Beitrag zur persönlichen Entwicklung eines Programmierers geschrieben. In diesem Beitrag habe ich mich selbst mehr als einmal wiedergefunden und gesehen, auf welcher Stufe der Evolution ich gerade stehe. Auf jeden Fall empfehlenswert!

Vorhang auf für… das MeshPack

Wie bereits zuvor beschrieben, ist Live Mesh nicht lediglich ein weiteres Synchronisationstool, sondern unter der Oberfläche eine Plattform für die Bereitstellung umfangreicher verteilter Funktionen, gegen die mit dem Live Framework programmiert werden kann. Und wie vermutet haben die Microsoft Startup Labs nun (Blog-Eintrag) als „Showcase“ die ersten 4 Mesh-Applikationen veröffentlicht: das MeshPack! (Zugang mit PDC-Code)

Die 4 Anwendungen lauten wie folgt:

  • Collaborative Crossword: Ein Kreuzworträtsel, welches von mehreren Benutzern zusammen (kollaborativ) gelöst werden kann.
  • CorkBoard: Digitales schwarzes Brett.
  • CrowdVote: Kollaboratives Umfragen-/Abstimmungstool.
  • MeshLists: Tool zur Erzeugung und zum Austausch von Listen.

Die Anwendungen basieren grundlegend auf den zur Verfügung gestellten Mesh-Objekten, z.B. den Feeds, um Informationen auszutauschen. Bei der Realisierung des Kreuzworträtsels kommt zudem Silverlight zum Einsatz, um die Mesh-Funktionalität mit einer RIA-Oberfläche zu verbinden.

Sicherlich ist keine dieser Anwendungen eine Killer-App und anscheinend spielen die Jungs bei Microsoft selbst noch mit dem Framework rum und erforschen, welche Ideen möglich bzw. sinnvoll sind. Persönlich vermute ich, dass im Hintergrund bereits größere Projekte angesetzt sind und umgesetzt werden, diese jedoch noch keinen Status erreicht haben, der es wert wäre, die Anwendungen das Licht der Welt erblicken zu lassen. Ich bin sehr gespannt, wie es hier weitergeht.

Links:

Playing around with… Silverlight 2

Halb beruflich, halb privat beschäftige ich mich derzeit mit Silverlight 2 und den Möglichkeiten, welche dieses bietet. Silverlight wird meiner Meinung nach in Zukunft eine verstärkte Rolle bei RIAs spielen und Microsoft hat mit Version 2 einen wichtigen Grundstein dafür gelegt. Endlich muss man sich als passionierter C#/.NET-Entwickler nicht mehr mit Javascript rumärgern, sondern bekommt eine integrierte Lösung an die Hand. Silverlight ist zweifelsohne auf einem aufsteigenden Ast, ob es wie mancherorts vermutet die Zukunft sein wird muss sich allerdings noch herausstellen.

Silverlight Toolkit

Ich spiele also derzeit ein wenig mit Silverlight rum und bin schon relativ begeistert, was die Möglichkeiten anbelangt. Ein Manko bisher waren die fehlenden Controls, doch mit dem Silverlight Toolkit und diversen Controls von Drittanbietern sind jetzt einige höchst interessante Lösungen verfügbar, welche die standardmäßig mangelhafte Funktionalität einbringen. Ich liebe die AutoCompleteBox und die Möglichkeiten des einfachen, aber mächtigen Item-Templatings. User Experience? Thumbs up!

Expression Blend AddIn-API

Weiterhin habe ich bereits eine frühe Version des Buches Hacking Silverlight 2 verfügbar und finde trotz einiger inhaltlicher Mängel die“Deep-Inside-Tipps“ (*Hacks*) wirklich gut. Zuvor war mir nicht bekannt, dass Expression Blend über eine AddIn-API verfügt, welche sich leicht ansprechen lässt um eigene Funktionalität zu Blend hinzuzufügen. Eine Einführung mit kleinem Beispiel dafür findet sich z.B. hier.

Intellisense in Expression Blend

Die AddIn-API von Blend macht es auch möglich, dass meine Gebete (oder zumindest eines) erhört wurden (wurde). Entwickler, die parallel mit VS 2008 und Blend arbeiten, kennen das Problem: in VS 2008 hat man keinen Design-Support (pfui Microsoft! wenigstens ein wenig Unterstützung in Form des Auswählen von Controls und Anzeigen von Properties wäre hilfreich gewesen… soll sich Silverlight auf diese Art durchsetzen? hier darf man sich auf VS 2010 freuen: „Also, the planned Visual Studio 2010 development platform will build further on Silverlight, featuring a fully interactive Silverlight designer.„). Dafür hat man im Visual Studio Intellisense für XAML. Genau anders herum ist es bei Expression Blend: schöner Design-Support, kein Intellisense. Des leidresistenten Entwicklers Lieblingstastenkombination wird Alt+Tab und alles ist schön… oder? Schöner geht’s mit XAML-Intellisense in Blend und genau das hat Stefan Dobrev von Telerik vorgestellt. Kaxaml (auch bei Codeplex gehostet) als AddIn für Expression Blend ist nicht perfekt, als Übergangslösung aber gut geeignet, bis Microsoft endlich mal mit einer eigenen Solution aufwartet…