Ottenere dati random da una query con LINQ to SQL

13 June 2010 maxgrante Nessun commento

Per un progetto avevo la necessità di estrarre randomicamente i dati presenti in una tabella “Articolo” contenente appunto articoli di categorie diverse.
Per fare questa operazione con classici statement SQL con mysql sarebbe stato abbastanza semplice, bastava utilizzare una query del tipo:

1
SELECT *, RAND() AS rand_value FROM Articolo ORDER BY rand_value;

Con il modello a oggetti di LINQ to SQL, era un filo più complesso (tra l’altro come base dati avevo SQL Server), per cui ho seguito questo howto:
http://weblogs.asp.net/fmarguerie/archive/2008/01/10/randomizing-linq-to-sql-queries.aspx

In buona sostanza è sufficiente andare a creare una nuova view:

1
CREATE VIEW RandomView AS SELECT NEWID() AS ID

E una funziona che possa richiamarla:

1
2
3
4
5
6
7
8
CREATE FUNCTION GetNewId
(
)
RETURNS uniqueidentifier
AS
BEGIN
RETURN  (SELECT ID FROM RandomView)
END

A questo punto il tutto si conclude andando ad aggiornare il modello LINQ to SQL per poter utilizzare la funzione utilizzare la seguente sintassi:

1
2
3
4
5
6
7
8
9
public IEnumerable<articolo> GetArticoliRandom(string AreaCode)
{
    IEnumerable < Articolo >  ArtList = (from art in _model.Articolo
        where art.AreaCode == AreaCode
        orderby _model.GetNewId()
        select art).Take(5);

    return ArtList;
}

Ovviamente il .Take(5) non serve necessariamente ma solo nel mio caso dove dovevo estrarre 5 articoli.

Share

Classe C# per parsing Atom da Blogspot e da PhpBB

Di seguito una semplice classe con due metodi per leggere (o come dicono gli americani, consumare) atom feed.
In entrambi i casi i due metodi ricevono in input l’URL del feed da parsare e ne restituiscono un Dictionary composito (semplicemente perchè mi serviva un tipo di dato di questo tipo).

In teoria sarebbe stato sufficiente l’utilizzo del solo metodo GetAtomItemsBlog() per leggere anche altri Atom, sfortunatamente però il tipo di Atom che esporta PhpBB non viene correttamente letto da questo metodo. Per ovviare al problema ho creato un secondo metodo GetAtomItemsForum() che utilizza la classe SyndicationFeed al posto di Atom10FeedFormatter.
Resta comunque interessante il primo metodo visto che va ad utilizzare la sintassi Linq.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class AtomRssReader
{
    public Dictionary<string , Dictionary<string, string>> GetAtomItemsBlog(string MyUrl)
    {
        XmlReader reader = XmlReader.Create(MyUrl);
        Atom10FeedFormatter atom = new Atom10FeedFormatter();
        Dictionary</string><string , Dictionary<string, string>> Ret = new Dictionary</string><string , Dictionary<string, string>>();
        Dictionary</string><string , string> Temp;
        if (atom.CanRead(reader))
        {
            atom.ReadFrom(reader);
            var items = from item in atom.Feed.Items.OfType<syndicationitem>()
                        select new
                        {
                            Id = item.Id,
                            Title = item.Title.Text,
                            Url = item.Links.Last<syndicationlink>().Uri.AbsoluteUri,
                            Published = item.PublishDate,
                            Updated = item.LastUpdatedTime,
                            Subtitle = item.Summary.Text
                        };
            foreach (var item in items)
            {
                Temp = new Dictionary<string , string>();
                Temp.Add("Title", item.Title);
                Temp.Add("Url", item.Url);
                Temp.Add("Published", Convert.ToString(item.Published.LocalDateTime));
                Temp.Add("Updated", Convert.ToString(item.Updated.LocalDateTime));
                Temp.Add("Subtitle", item.Subtitle);
                Ret.Add(item.Id, Temp);
            }
        }
        reader.Close();

        return Ret;;
    }

    public Dictionary</string><string , Dictionary<string, string>> GetAtomItemsForum(string MyUrl)
    {
        Dictionary</string><string , Dictionary<string, string>> Ret = new Dictionary</string><string , Dictionary<string, string>>();
        XmlReader reader = XmlReader.Create(MyUrl);
        SyndicationFeed feed = SyndicationFeed.Load(reader);
        Dictionary</string><string , string> Temp;

        foreach (var item in feed.Items)
        {
            Temp = new Dictionary</string><string , string>();
            Temp.Add("Title", item.Title.Text);
            Temp.Add("Published", Convert.ToString(item.LastUpdatedTime.LocalDateTime));
            Temp.Add("Updated", Convert.ToString(item.LastUpdatedTime.LocalDateTime));
            Temp.Add("Url", item.Id);
            Temp.Add("Subtitle", ((TextSyndicationContent)item.Content).Text);
            Ret.Add(item.Id, Temp);
        }

        return Ret; ;
    }
}

Share

Inaugurazione categoria Asp.NET

Da oggi apro definitivamente la categoria Asp.NET.
Avendo cominciato da qualche mese a programmare in C# mi sembrava doveroso aprire una categoria nella quale postare qualche utile tips&tricks.

Buona lettura a tutti.

Share

Abilitazione registrazione blog

28 April 2010 maxgrante Nessun commento

Da oggi e’ possibile registrarsi al blog. ( Finalmente ho trovato un sistema di captcha come si deve… :-D )
Registratevi, scrivete, scrivete e scrivete ancora… ;)

Share

Linux/Ubuntu, usare Access tramite ODBC con PHP

25 February 2010 maxgrante Nessun commento

Linko un ottimo articolo che spiega come utilizzare Access da php su Linux utilizzando ODBC.
L’articolo fa riferimento ad Ubuntu, comunque in linea di massima è applicabile su qualunque altra distro.

http://www.lorenzoingrilli.it/database-access-mdb-da-linux-via-odbc

Share