Tuesday, January 4, 2011

Framework für iPhone, iPod Touch und iPad Webapp

Sollte ein Entwickler eine Webseite oder eine Webapplikation für einen iPhone, iPod Touch und iPad entwickeln, so empfehle ich euch folgendes free open source Framework iWebKit (http://iwebkit.net/).
photoiWebKit besteht aus mehreren Dateien, welche Ihnen ermöglicht auf einfacher weiße eine kompatibel Website oder Webapplikation für iPhone, iPod Touch und iPad zu erstellen. Das Kit ist für jedem  zugänglich und sehr einfach zu verwenden. Außerdem es ist gut dokumentiert und es gibt auch genügend Beispiele. iWebKit ist ein großartiges Werkzeug, weil es sehr einfach zu bedienen, extrem schnell, kompatibel und erweiterbar ist.

Die folgende Seite wurde mit diesem Framework erstellt: http://www.provincia.bz.it/meteo/mobile/

Monday, January 3, 2011

LINQ & Expressions costruzione a runtime

Questo post vi servirà come un piccolo aiuto per capire meglio i miei post futuri che parleranno di jQuery (http://jquery.com/) è jqGrid (http://www.trirand.com/blog/). Qualche volta è necessario costruire una LINQ  query a runtime, che non è una cosa triviale. Per imparare e per avere un piccolo aiuto, io ho utilizzato un istrumento chiamato Expression Tree Visualizer (http://msdn.microsoft.com/en-us/library/bb397975(VS.90).aspx), che permette di vedere la costruzione delle espressioni. Expression Tree Visualizer lo trovate negli esempi di VS2008.

image

Praticamente ho prima scritto la LINQ query che mi interessava. Questa la ho analizzata con Expression Tree Visualizer è ho infine riscritto la stessa LINQ query utilizzando solamente le espressioni (costruzione di un expression tree). Perché tutta questa fatica? Per scrive LINQ a runtime.

Esempio:
Questa LINQ query

cells => cells["Description"].eq(cells["Description"].Create("Daniel"));
è stata trasformata in
ParameterExpression param = Expression.Parameter(typeof(Dictionary<string, GridCell>), "cells");
//cells["Description"]
ConstantExpression pKey = Expression.Constant("Description");
MethodCallExpression dicCall = Expression.Call(param, "get_item", null, pKey);
//cells["Description"]
ConstantExpression pKey1 = Expression.Constant("Description");
MethodCallExpression dicCall1 = Expression.Call(param, "get_item", null, pKey1);
//.Create("Daniel")
ConstantExpression pStrValue = Expression.Constant("Daniel");
MethodCallExpression createCall = Expression.Call(dicCall, "Create", null, pStrValue);
//operation 
MethodCallExpression eqCall = Expression.Call(dicCall1, "eq", null, createCall);

Infine vorrei fare farvi nottare, che per qualcuno di voi potrà essere abbastanza l’utilizzo di queste librerie Dynamic LINQ (http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx).

Wednesday, November 3, 2010

Log4Net: esempio di configurazione

Un piccolo suggerimento per chi di voi utilizza Log4Net (http://logging.apache.org/log4net/index.html) ma utile: Invece di utilizzare log4net.Appender.FileAppender sarebbe consigliato l’utilizzo di log4net.Appender.RollingFileAppender, che vi da decisivamente più funzionalità per esempio potete impostare la grandezza massima del file di log o anche potete specificare che il file venga rinominato con un “date pattern”.

Ecco un esempio di configurazione:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </configSections>
    <log4net debug="false">
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender, log4net">
            <file value="C:\xxx\xxx_Log4Net" />
            <appendToFile value="true" />
            <rollingStyle value="Composite" />
            <datePattern value=".yyyyMM'.log'" />
            <maxSizeRollBackups value="-1" />
            <maximumFileSize value="50MB" />
            <layout type="log4net.Layout.PatternLayout, log4net">
                <conversionPattern value="%d [%t] %-5p %c - %m%n" />
            </layout>
        </appender>
        <root>
            <priority value="ALL" />
            <appender-ref ref="RollingLogFileAppender" />
        </root>
    </log4net>
</configuration>

Qualche note:

Impostando la proprietà RollingStyle uguale a Composite istruisco a Log4Net che il file corrente si chiami xxx_Log4Net e i file successivi vengano denominati con il seguente pattern .yyyyMM'.log' (yy sta per anno e MM sta per mese). Per essere più esatti passato un mese il file corrente xxx_Log4Net verrà rinominato a xxx_Log4Net.yyyy.MM.log. Inoltre se il file supera la grandezza di 50Mb verrà creato un nuovo file con il nome xxx_Log4Net.1.

Tuesday, October 26, 2010

How to post your source code on blogspot

I am using SyntaxHighlighter (http://alexgorbatchev.com/SyntaxHighlighter/) for formatting and highlighting source code on blogspot and I will explain in this post step by step how to set it up. Btw: For writing my blogs I am using Windows Live Writer with the plug-in Precode (http://precode.codeplex.com/) which gives support for SyntaxHighlighter and snippet indentation.

1) From the navigation menu of blogspot select DesignEdit HTML. Add following lines:




2) For posting a piece of c# source code it is enough to wrap it between:

source code

HAPPY POSTING!!

Tuesday, September 21, 2010

Just Another String Enum

Enum sono molto utili. Uno dei problemi degli Enum in .NET è la mancanza di supporto per stringhe. Infatti questi possono essere solamente di tipo numerico.
Vediamo come aggiungere il supporto delle stringhe agli Enum. L’idea è di utilizzare un “Extension Methods” per aggiungere alla classe Enum il metodo GetStrOfEnumMemberAtt e per enumerare i valori con le stringhe utilizziamo la classe EnumMember.

La seguente classe contiene “Extension Methods” che poi utilizzeremmo per accedere alla stringa. Vorrei fare notare, che questa classe utilizza un oggetto Dictionary come cache per essere più performante.

public static class EnumExtensions
{
    //cache
    private static Dictionary<Enum, string> _stringValues = new Dictionary<Enum, string>();

    public static string GetStrOfEnumMemberAtt(this Enum value)
    {
        if (!_stringValues.ContainsKey(value))
        {
            //Add to cache
            Type type = value.GetType();
            FieldInfo fi = type.GetField(value.ToString());
            EnumMemberAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumMemberAttribute), false) as EnumMemberAttribute[];
            if (attrs.Length > 0 && !string.IsNullOrEmpty(attrs[0].Value))
            {
                _stringValues.Add(value, attrs[0].Value);
            }
            else
            {
                _stringValues.Add(value, value.ToString());
            }
        }
        return _stringValues[value];
    }
}

Questo è un esempio di come decorare gli Enum con le stringhe:

public enum MachineTypes{
    [EnumMember(Value = "Motorcycle")]
    MOTO,
    [EnumMember()]
    BICYCLE,
    CAR
}

Poi è semplice, per accedere al stringa basta chiamare il metodo GetStrOfEnumMemberAtt come in questo esempio:

//s1=Motorcycle
string s1 = MachineTypes.MOTO.GetStrOfEnumMemberAtt(); 
//s2=BICYCLE
string s2 = MachineTypes.BICYCLE.GetStrOfEnumMemberAtt();
//s3=CAR
string s3 = MachineTypes.CAR.GetStrOfEnumMemberAtt();

Monday, September 20, 2010

Performanceprobleme??? Hier die Lösung

Jeder seriöse Webentwickler sollte den Artikel “Best Practices for Speeding Up Your Website” (http://developer.yahoo.com/performance/rules.html) von Yahoo Developer Network kennen.
Hier nochmals eine kleine Zusammenfassung der wichtigsten Regeln:

  • Minimieren Sie HTTP-Requests
    • Alle Script Dateien sollten zu einer großen Script Datei zusammengeführt werden, das gleich gilt für CSS Dateien.
  • Verwenden Sie einen Content Delivery Network
  • Verwenden Sie eine Expires oder Cache Header
  • Verwenden Sie Gzip Components
  • Referenzieren Sie Stylesheets im Header
  • Referenzieren Sie Scripts auf der Unterseite
  • Vermeiden Sie CSS Ausdrücke
  • Script und CSS sollten in externen Dateien vorliegen
  • Reduzieren Sie DNS-Lookups
  • Verkleinern Sie Script und CSS Dateien
    • Entfernen Sie unnötige Zeichen (Leerzeichen, Zeilenumbruch und Tabulator)
    • Entfernen Sie Kommentare und unnötigen Code

Nachdem wir ein bisschen die Theorie aufgefrischt haben nun die Praxis:
Die NET-Bibliothek COMBRES (http://combres.codeplex.com/) ermöglicht das Verkleinern, die Kompression und die Kombination von Script und CSS Dateien. Zudem erlaubt diese das Zwischenspeichern (= Caching) von Script und CSS Ressourcen für ASP.NET und ASP.NET MVC Web-Anwendungen.

Saturday, September 18, 2010

Un estensione utile per l’oggetto NameValueCollection

Queste poche righe di codice permettono di trasformare una NameValueCollecition in un oggetto Dictionary<string, string>.

public static class NameValueCollectionExentsions
{
    public static IDictionary<string, string> ToDictionary(this NameValueCollection source)
    {
        return source.AllKeys.ToDictionary<string, string, string>(x => x, x => source[x]);
    }
}

Cosi facendo sarà possibile utilizzare LINQ per fare delle queries.

IDictionary<string, string> queryStr = context.Request.QueryString.ToDictionary();
queryStr.SingleOrDefault(x => x.Key.Equals("Value", StringComparison.InvariantCultureIgnoreCase));