in

DotNetMarche

.NET Framework User Group delle Marche

This Blog

Syndication

ExternalBlogs

May 2009 - Posts

  • Come settare il valore di default per un campo di tipo SPFieldBoolean

    L'altro giorno mi è capitato di dover gestire un campo di tipo boolean (si/no) di una particolare lista SharePoint, attraverso il modello ad oggetti. La valorizzazione a fronte dell'inserimento o della modifica di un elemento di tale lista, risulta...
  • Redmine: a trick to import data from Mantis

    Today I decided to give Redmine a try as my new project management and bug tracking solution, mainly cause I wanted to try its integration with Subversion (given the fact that setting up an integration between Mantis and Subversion is a really painful...
  • Going in production as often as you can

    I really care the concept of “going in production”, because it is the moment when the software bring to life. Going in production can be sometimes a really difficult thing to do, and there are a lot of reasons behind it. First of all we have the syndrome of “It works on my machine”. The software [...]
  • XElement and hexadecimal value 0×0C is an invalid character

    I’ve a little library that build excel files in openXml format. It is based on LINQ to XML, and permits you to open an excel file with open xml sdk, then manipulate the content and showing it to the user. Today for a particular set of data I got hexadecimal value 0×0C, is an invalid character This is [...]
  • Visual Studio Database Edition, First steps

    I began using Visual Studio Database Edition today, I did not used it before because I’m the only one in the team that have this edition, others developers used VS professional, but I’m the one who cares of database in this project, quite all modifications are done by myself, so I decided to create a [...]
  • mstest environment for unit testing

    I’ve quite always used Nunit for unit testing, I had some little project with mbUnit and a try with xUnit, but I feel comfortable with Nunit so I never had the need to switch to other environment. Now I wanna take a shot to msTest, mainly because it is fully integrated with visual studio and [...]
  • jQuery tip #7 – gli eventi globali ajax

    Nel codice relativo all’esempio del tip 7 è stato aggiunto un controllo di questo tipo per simulare eccezioni che si verificano nella pagina del servizio.

    String code = Request["Code"];
    if (code.StartsWith("B", true, null)) 
        throw new ArgumentException("Error in parameter");

    In questo caso quando si richiedono i dati di un cliente il cui codice inizia per B viene lanciata una eccezione. Il problema in questo caso è che lasciando il codice javascript del tip 6, si ha un spiacevole inconveniente. Quando si richiede un cliente con codice che inizia con B, viene impostato lo stato di attesa come spiegato nel tip precedente, ma purtroppo l’interfaccia rimane cosi, bloccata, senza che lo stato di attesa se ne vada.

    Questo avviene perchè nel caso di eccezione la pagina aspx restituisce il classico messaggio di eccezione.

    image

    jQuery tenta di convertire questo HTML in JSON ma non riesce, e per questo non richiama la funzione callback specificata nella getJSON. Purtroppo questo comporta avere una pagina che rimane in uno stato non utilizzabile.

    La soluzione risiede negli eventi callback ajax esposti da jQuery. La chiamata getJSON è infatti una delle tante offerte da jQuery per utilizzare funzionalità ajax, e per questo condivide un set di funzionalità standard, come ad esempio la possibilità di utilizzare eventi specifici relativi alle chiamate ajax. Questi eventi possono risolvere questo problema in maniera molto elegante

    $(function() {
        $('.maindiv')
            .ajaxStart(function() {
                console.log('ajaxStart');
                $(this).log('this ajaxStart').setwait();
            })
            .ajaxError(function(event, request, settings) {
                console.log('ajaxError');
                $(this).log('this ajaxError').clearwait();
            })
            .ajaxSuccess(function(evt, request, settings) {
                console.log('ajaxSuccess');
                $(this).log('this ajaxSuccess').clearwait();
            });
    
        $('[id=btnGetData]').log('button').click(function() {
            var button = this;
            var code = $('[id=txtCode]').val();
            $.getJSON(
                    '/Tip7/CustomerService.aspx',
                    {
                        Code: code
                    },
                    function(result) {
                        //Here result object has the same properties as Customers
                        var showresult;
                        for (p in result)
                            showresult += p + ': ' + result[p] + '<br />';
                        $('.result').html(showresult);
                    });
            return false;
        });
    });

    Come si può notare, nella prima parte sono stati attaccati al div principale alcuni eventi ajax, con l’aggiunta di qualche funzione di log per firefox che aiuta a capire quando vengono lanciati. Nel primo, ajaxStart, viene impostato lo stato di attesa, mentre in ajaxError e ajaxSuccess viene semplicemente rimosso lo stato di attesa. In questo modo sia in caso di successo, che in caso di fallimento, lo stato di attesa per il div principale viene sempre impostato correttamente.

    alk.

    Tags:

  • Come abilitare il menu delle variations per cambiare lingua ad un sito MOSS 2007

    Le variations permettono di abilitare un meccanismo di gestione multilingua dei contenuti all'interno di siti MOSS 2007 (versione sia standard che enterprise). Una volta configurate correttamente (ed installati i relativi language pack), è possibile...
  • Windows 7 RC acquisition from DV camera

    I hope I can help others because it took me about a couple of hour to find a solution to this problem. I have a mini DV camera SONY DCR CH51E and windows 7 rc 1. When I connect the camera to the pc the first time I see a baloon in the systray area that [...]
  • Occam’s Razor, probably is the better principle to keep in mind

    This morning I completely wasted 2 hours of my life, here is the history. I’m rewriting some nant script for a series of articles in italian language, this morning I did some modification to the base script, and I applied this new base script to a solution with 6 projects. Everything went fine, except for the Test [...]
  • Asp.Net, ObjectDataSource and Castle Windsor

    I’m restructuring a portion of a site, it is well structured, and all logic is inside business classes in another assembly, and they are accessed with ObjectDataSources. My problem is that with the new structure I cannot refer to the concrete classes anymore, but I need to resolve them with an IoC container, like Castle [...]
  • Post-MOSS SP2 : license says “trial edition”

    Gabriele, sul newsgroup dedicato a SharePoint segnala un importante bug relativo il post aggiornamento alla SP2 si MOSS. Leggete con attenzione … mannaggia a questi indiani!!
  • Saving a generic Object property with nhibernate

    In a old post I explained how to save an object in XML format in database with a UserType. Since this technique worked well I decided to use it in another situation. Now I have an object that have a property of type Object, and I want to be able to save xml serialiation of [...]
  • jQuery tip #6 &ndash; segnalare all&rsquo;utente le chiamate ajax

    Nel tip5 ho mostrato come interrogare il server con getJSON, per questo tip ho semplicemente aggiunto nella pagina CustomerService.aspx una istruzione Thread.Sleep(3000) per fare attendere tre secondi il rendering della pagina. Lo scopo è simulare una operazione lunga.

    In situazioni in cui la risposta del server non può essere stimata (praticamente sempre), è necessario mostrare all’utente un qualche segnale che l’operazione è in corso, in modo che non possa più premere nel bottone, ma soprattutto sia avvertito visualmente che il sistema non è bloccato ma sta facendo qualche cosa.

    Questa operazione è cosi frequente che è stata implementata come plugin nel file jqueryext.js, le due estensioni si chiamano quindi setwait() e clearwait(), rispettivamente per impostare uno stato di attesa per un div e riportare il div alla situazione originaria.

    (function($) {
    
       $.fn.setwait = function(options) {
          var settings = $.extend({
             slidecss: 'waitindicatormasx',
             imagecss: 'waitindicator',
             waitoffset: 200
          }, options || {});
         

    La prima parte della funzione è la classica dichiarazione di plugin jQuery, la funzione $.extend( serve invece per comporre due oggetti, e verrà spiegata in dettaglio in un prossimo tip.

      var context = this;
          //      debugger;
          context[0].timer = setTimeout(function() {
             var position = context.position();
             var thediv = context;
             var innerslide = $('<div style="width:' + thediv.width() + 'px; height:' + thediv.height() + 'px" class="' + settings.slidecss + '" />')
                .css('opacity', 0.5);
             var progress = $('<div style="width:' + thediv.width() + 'px; height:' + thediv.height() + 'px" class="' + settings.imagecss + '"/>');
             thediv.prepend(innerslide)
             thediv.prepend(progress);
             context[0].innerslide = innerslide;
             context[0].progress = progress;
          }, settings.waitoffset);
          return this;

    Il resto della funzione non fa altro che creare un timer con la funzione setTimeout. In questo modo lo stato di attesa viene impostato solo allo scadere del timer, che per default è impostato a 200 millisecondi; grazie a questo piccolo offset, se il server risponde prima di 200 millisecondi lo stato di attesa non viene mai impostato. Grazie a jQuery lo stato di attesa viene impostato creando un nuovo div, impostandone le dimensioni al div target, sovrapponendolo al div originale con una opacità dello 0.5. In questo modo il contenuto originale del div si schiarisce perchè viene visualizzato sotto un div con sfondo bianco e opacita 50%, poi viene inserito un altro div con al centro una immagine gif animata per mostrare l’attesa.

    La funzione clearwait non fa altro che controllare se il timer è scaduto, in caso contrario semplicemente lo annulla, altrimenti rimuove i due div. Gli stili base dei due div sono fatti cosi, ma possono essere modificati

    .waitindicatormasx 
    {
       position: absolute;
       background-color: White;
       z-index: 2;
    }
    
    .waitindicator 
    {
       position: absolute;
       background-image: url(Images/ajax-loader3.gif);
       background-repeat: no-repeat;
       background-position:center;
       z-index: 3;
    }

    è importante il posizionamento assoluto per sovrapporsi al div originale, per il resto si può magari cambiare il colore, tipo il classico giallino.

    Ora che si è creata questa funzione, usarla è banale.

    $(function() {
        $('[id=btnGetData]').log('button').click(function() {
            var button = this;
            var code = $('[id=txtCode]').val();
            $('.maindiv').setwait();
            $.getJSON(
                    '/Tip6/CustomerService.aspx',
                    {
                        Code: code
                    },
                    function(result) {
                        //Here result object has the same properties as Customers
                        $('.maindiv').clearwait();
                        var showresult;
                        for (p in result)
                            showresult += p + ': ' + result[p] + '<br />';
                        $('.result').html(showresult);
                    });
            return false;
        });
    });

    Come si può vedere il div identificato dalla classe “maindiv” viene posto in stato di attesa alla pressione del bottone, nella funzione callback la prima cosa che si fa è rimuovere lo stato di attesa, e poi modificare il div con i nuovi dati. La pagina principale ora è fatta cosi

        <div class="maindiv">
            <asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
            <asp:Button ID="btnGetData" runat="server" Text="Button" />
            <div class="result">
            </div>
        </div>

    Tutti i controlli sono racchiusi nel div mainDiv, premendo il bottone per la ricerca si può notare come tutto il contenuto sia schiarito e grazie al div sovrapposto, è impossibile cliccare ancora nel tasto e quindi fare più richieste.

    image

    Grazie al fatto di avere incluso la funzionalità in un plugin, usarla è solo questione di due righe di codice.

    alk.

    Tags:

  • Castle Windsor WCF Services Resolution Facility

    I have to admit I am not a huge fan of the automatic proxy generated code that you can obtain with svcutil.exe or using a standard Visual Studio service reference; mainly because it’s bloated with a lot of unneeded code, especially if you develop the...
More Posts Next page »
Powered by Community Server (Commercial Edition), by Telligent Systems