Gestion des erreurs en ASP.NET MVC

Article publié dans le magazine Programmez ! – Avril 2014 – N° 173

Lors de la conception d’une application web, gérer le comportement du système en cas d’erreur est important et ne devrait pas être laissé au hasard. D’une part, visualiser une page système peu accueillante, non stylisée, et loin des couleurs du site n’est pas toujours agréable pour l’utilisateur qui vient en plus de recevoir une erreur. D’autre part, si certains paramétrages ne sont pas effectués, l’utilisateur pourrait avoir accès aux détails techniques de l’exception. Un visiteur mal intentionné pourrait se servir de ces détails pour accumuler des connaissances sur la structure technique du site et trouver plus facilement une faille de sécurité à exploiter. Ainsi, il appartient à l’équipe de réalisation du site de déterminer en amont le niveau de détails d’erreur à délivrer à l’utilisateur, les codes d’erreur HTTP à renvoyer en fonction des situations et les pages d’erreur qui seront affichées. En somme, il s’agit de décider d’un comportement applicatif en cas d’erreur qui soit uniformément suivi au cours des développements.

ASP.NET MVC offre de nombreuses solutions pour gérer une exception de manière centralisée et rediriger vers une ressource en particulier. Gérer les erreurs peut donc se faire de plusieurs façons et peut s’adapter à divers scénarios. Ces différentes manières seront exposées au cours de cet article, du niveau le plus global à celui le plus fin.

Continue reading “Gestion des erreurs en ASP.NET MVC”

Advertisements

How to display little temporary javascript messages to the user ?

Hello everyone,

Today, I’ll talk about displaying little notification messages at the bottom of a web page, and how to make them appear and vanish after a few seconds in a customizable way, thanks to JQuery. Let’s say we need to display messages that would stack up against each other, and each would appear and disappear after a specified time. We want to :

–          Style the notifications (error, validation…)
–          Style the whole notification template and put whatever we want in it
–          Notifications should anchor to the bottom of the page, wherever we’re scrolling at.
–          All this within a jquery plugin ?

To ease our task, we’d rather use jquery template.

First, refer the scripts you need at the end of the page to prevent them from slowing html rendering :

  <script src="Scripts/jquery-1.9.1.js"></script>
    <script src="Scripts/jquery-tmpl.js"></script>
    <script src="Scripts/notificationMaker.js"></script> <!--our plugin-->

Then create your page. For the sake of the demo, we add 3 buttons, one for displaying negative messages, one for good messages, the last one for custom templated messages. We add a long text excerpt to check that scrolling doesn’t affect our notification messages anchor.

 <div id="whole">
            <div id="buttons">
                <textarea id="myMessage"></textarea>
                <br />
                <button id="notification-negative">post alert</button>
                <button id="notification-positive">post good message</button>
                <br />

                <button id="templated-notification">post custom message</button>
            </div>
            <div id="content">
                    "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
            1914 translation by H. Rackham

             "... and so on ... (big text to show even when scrolling notification messages stay put"
            </div>
        </div>

Then write the script that will use our notification jquery plugin. I just wrote an example, but you can use it any way you want. First function will use a simple css class for styling good messages. Second function will use a different css class for errors then specify how many milliseconds the message will appear.

<script type="text/javascript">
        $(document).ready(function () {
            $("#notification-positive").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        cssClass: "notification-message",
                    })
                ;
            });
            $("#notification-negative").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        cssClass: "notification-error",
                        time:4000,
                    })
                ;
            });
       });
    </script>

A third function specify a custom template, giving its selector.

$("#templated-notification").click(function () {
                var value = $("#myMessage").val();
                $.postMessage(value,
                    {
                        template: "#my-message-template",
                    });
            });

And here’s the template

 <script id="my-message-template" type="text/html">
        <div class="templated-part">
            <p>{{= Message }}</p>
        </div>
    </script>

Of course you could build the template the way you want, with pictures, other div, span or whatever inside it. Just evaluate the “Message” variable wherever you want to show the text message.

Now let’s show the interesting part, the plugin part  with all comments :

(function ($) {
    var notificationMaker = {
        messageArea: null,
        init: function () { //just once at the beginning to insert the message area once into the DOM
            if (notificationMaker.messageArea)
                return;
            messageArea = document.createElement('div');
            $(messageArea).addClass("notification-area"); //style the notification area in stylesheet if you don't want it that way
            $("body").append(messageArea);
        },
        //method that shows the messages for a specific time and with animations
        showMessage: function (elm, time) {
            $(elm).slideToggle();//or use whatever animation you want
            setTimeout(function () {
                $(elm).slideToggle({
                    complete: function () {
                        messageArea.removeChild(elm); //important, remove the element from DOM so that DOM doesn't grow too much
                    }
                });
            }, time);
        },
        methods: {
            //options : cssClass, custom template, time to display the message
            postMessage: function (message, options) {
                var element = null;
                options = (!options) ? {} : options;
                var time = (options.time) ? options.time : 3000; //sets a default time if none specified
                if (!options.template) { //if no template, that's gonna be a paragraph
                    element = document.createElement('p');
                    if (options.cssClass) //if there's a specified css class
                        $(element).addClass(options.cssClass);
                    $(element).text(message); //sets the text
                }
                else {
                    element = $(options.template).tmpl({ Message: message })[0]; //apply a jquery template,
                    //take the first of the array a jquery template will return an array
                    //we need an object only to remove it from DOM later
                }
                $(element).hide();
                $(messageArea).append(element);
                notificationMaker.showMessage(element, time);
                return this;
            },
        }
    };

    //add the plugin method to jquery methods, beware not to replace any jquery native methods.
    $.postMessage = function(method) {
        var methods = notificationMaker.methods;
        if (typeof method === 'string') {
            if (method !== "")
                return methods.postMessage.apply(this, arguments);
            else return this;
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.notificationMaker');
        }
    };
    notificationMaker.init();

})(jQuery);

That way, it is clipped to the page’s bottom, no matter if you scroll the page, thanks to a custom JQuery plugin.

Here’s the zipped project if you want the whole thing with css :

Client side notifications sample

Enjoy 😉

My changes in kendo external templates are ignored by IE

Hi guys,
Again a very simple tip on kendo : if you’re using kendo external templates, you might be wondering why your recent changes aren’t reflected, or even why recently new added templates can’t be found when running your site within Internet Explorer.

IE in particular will cache your kendo template files in folder Temporary Internet Files. Feel free to empty that folder to get your last modifications !

Kendo autocomplete box and server filtering

Hello all,
A very simple thought today but as it took me some time to figure it out, I thought that little post could make you spare some.

I used the autocomplete box from kendo UI bound with a remote datasource. Based on the user input, server returned a set of matching words, processing quotes for example for a google-like exact search. But the autocomplete box kept filtering client-side too, looking for quotes in the results set and filtering all my server results…. I finally figured out that setting “serverFiltering = true” on the datasource itself stopped the client-side filtering !
Happy coding !

var dataSource = new kendo.data.DataSource({
      transport: {
         read: { url : "http....",
        },
      success: function (response) {
         o.success(response);
       }
 },
 serverFiltering: true, //set it to true to stop client-side filtering
 total: 5, //five results only
 optionLabel: "Type in a...",
 });

myAutoComplete.kendoAutoComplete({
 dataSource: dataSource,
 dataTextField: "toto",
 dataValueField: "titi",
 …
 )} ;

Parsing an xml to get a c# object with dynamic type

Okay, okay you’re right, thank you Leo 😉 So let’s render unto Caesar the things which are Caesar’s… Microsoft took into account the power of those weakly-typed languages such as JavaScript, the ones which allow you to deal with types you don’t know yet. Within .NET 4, they release the dynamic type, in reference to those languages, which they specifically call dynamic languages.

So now, if you derive from DynamicObject to create your own one, you can use pretty much the same code I used previously in JavaScript to get a c# object from Xml. You can create any property you’d like at runtime, only by accessing it like an array. Just write myDynamic[“house”]=whatever and it gets created in the meantime. In the end, you’ll be able to access any property you created in a totally transparent manner like myDynamic.house….

Plus, with the

TryConvert(ConvertBinder binder, out object result)

you can get the statically typed object you were expecting if you ever need a strongly typed object.

Enough of this talking, here you can find some more explanations about dynamic and how to take advantage of it :
http://msdn.microsoft.com/en-us/library/dd233052.aspx
http://msdn.microsoft.com/en-us/library/dd264736.aspx
http://msdn.microsoft.com/en-us/library/dd264741.aspx

and here’s the code:
https://docs.google.com/open?id=0BwW7tKeWhpnKcFZUakpJVENvOWs

Parsing an xml to get a javascript object

Parsing an xml with JavaScript to get the information you want is pretty easy. But parsing any xml to dynamically get exactly the equivalent plain JavaScript object may require a little algorithm. So you’re going to deal with a little of reflection, which is pretty easy with a weakly-typed language such as JavaScript, and you wanna build a recursive function to loop through your xml tree.
As I didn’t find a generic method on the web to get a JavaScript object from an xml, I built my own little method. So, if you’re in the same situation, here’s the code now :
Continue reading “Parsing an xml to get a javascript object”

WPF TabControl + Mvvm datatemplate binding = Attached properties are lost

At the moment, I’m trying to create some kind of chat with WPF following mvvm pattern so that I can learn and have fun at the same time. Must admit I’m a total beginner in WPF and decided to learn from Josh Smith’s very interesting and teaching article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030 and get inspired  by his workspaces model. Just like his demo, I needed tabs displaying the same view but with different datacontexts of course since one tab would be dedicated to one conversation (we don’t want to intermingle recipients !). I really admired the elegant and simple way of applying a view to a viewmodel, no code behind, everything centralized in a uncoupled resources dictionary :

<DataTemplate DataType="{x:Type vm:AllCustomersViewModel}">
    <vw:AllCustomersView />
  </DataTemplate>

Moving forward in building my project based on these patterns, creating my “conversation” view, attached properties came into play. I needed a particular behavior on one UI element to be triggered by another control’s itemssource’s event (on new item for instance). Searching the web, I heard about attached properties. But imagine my surprise when I saw my attached property only working for the first tab…

Continue reading “WPF TabControl + Mvvm datatemplate binding = Attached properties are lost”