List Random Order in .NET using Linq

Posted on 5:03pm 1/27/2009 by Bruno Silva in .NET, Programming

While refactoring some C# code I came across some lines that seemed a bit awkward. I was trying to sort a list or an array randomly. That code was written before Linq came into the .Net Framework, so now I was able to figure out a new approach.

Since Linq to Objects has some similarities with SQL, I got the idea of trying the same approach that I used several times in SQL, which was ordering a SELECT statement using ORDER BY RAND().

The result is shown bellow.

It uses the Extension Methods syntax of Linq to save some bytes on the source code :-P

Using web.config for custom configuration settings

Posted on 10:13am 1/22/2009 by Bruno Silva in .NET, ASP.NET, Programming, Web

If you are an ASP.NET developer you must be familiar with web.config. Something that maybe you haven’t tried yet is to create custom configuration sections to store you application specific settings. Bellow you can see a web.config file that uses a custom configuration section. In the configuration/configSections element you must define which class is responsible for handling your configuration section. Then you can add your custom settings to the file as shown bellow.

The usage of your settings is shown bellow. The configuration section handler class is used in order to access the configuration properties.

I’ve shown you the usage of a class called SiteSettings, but how does it’s definition look? It is a class that inherits the ConfigurationSection class. The configuration section properties are defined by adding public properties that correspond to Configuration Elements. While adding these properties you can define the name of the XML node that you will use in the web.config file and either if the property is required or not. In the example bellow you can see the Singleton design pattern in order do avoid creating several instances of the class and loading the section from the configuration file each time I access the values.

In this example, we only have one configuration property. It is defined in the class bellow. It corresponds to a contact information. Each property of this class correspond to an XML attribute, and by using annotations you can define the name of the XML attribute, it’s default value, if it is required and even add validators such as regular expression validators. You can use several variable types such as strings, integers and event enumerables.

By using custom configuration settings this way instead of accessing ConfigurationManager.AppSettings as a dictionary of string values you get intellisense while using configuration settings, and best of all, automatic validation of the types, constraints and structure of the settings (checked when the settings are accessed for the first time).

The full demo project is available for download. I hope it gets useful to you.

Linq - Adding element to collection, Union vs Concat

Posted on 11:45am 1/21/2009 by Bruno Silva in .NET, Programming

Some time ago while developing a project I came across a problem related to Linq to Objects. I wanted do join a single object with a collection in order to transverse them with a foreach statement (the item was not allways present and I wanted to treat it as a regular element in the original collection).

Using the intellisense to find a Linq to Objects extension method that fitted my needs I didn’t find that particular functionality, but I thought about an alternative: creating a collection with the single element and joining the two collections with one of the two extension methods that seem promising to this new task: Union and Concat.

After reading the documentation and writing the example above I became aware of the difference. Union acts as a mathematical set operator, adding the elements of both lists into a single list without repeated elements. Contat, by the other hand keeps the repeated elements.

Novo portal Sapo Kids

Posted on 5:12pm 1/16/2009 by Bruno Silva in Freeware, Sapo, Software, Web

Foi lançado hoje um novo portal português destinado aos mais novos. É o Sapo Kids! Além de diversos conteúdos lúdicos e didácticos reunidos a partir dos diversos serviços do mundo Sapo, conta com parcerias como a Porto Editora ou até mesmo o MIT.

Realço a integração do Scratch no portal. O Scratch que nasceu no MIT permite aos mais novos criarem animações interactivas de forma simples e divertida enquanto aprendem. O Sapo Kids tem a plataforma Scratch totalmente em Português, tornando-a ainda mais atractiva às crianças portuguesas.

Antes mesmo do projecto criar raízes em Portugal já existia uma escola pioneira a utilizar o sistema do MIT. Espero que outras lhe sigam o exemplo agora com este portal Português.

Mais informações no site http://kids.sapo.pt

O marketing nas grandes superfícies…

Posted on 9:14am 12/19/2008 by Bruno Silva in My Life

No outro dia fui ao Media Markt de Sintra para comprar um pack de 4 pilhas recarregáveis. Encontrei um pack da Duracell a 14 euros (ou 13.90 e tal, whatever). Ao lado estavam um pack de 2 pilhas a 6 euros.

Portanto,

  • 6 euros x 2 packs (2 pilhas cada) = 12 euros
  • 14 euros * 1 pack * (4 pilhas) = 14 euro

O senso comum não nos diz que os packs de maior número de unidades deve sair mais barato? Ou pelo menos ter o mesmo preço? O meu diz que sim. Ou é um engano de marcação de preço, ou stocks distintos em que um deles ainda foi adquirido com preço antigo.

Mas a hipótese que me parece mais interessante é ser uma estratégia de marketing para ganharem uns trocos. Se toda a gente pensar como eu que os packs maiores saem mais barato ou igual, imaginem os vários 2 euros que ganham em cada pack (já nem falando na poupança na embalagem).

Tive sorte de geralmente ter a mania de comparar os preços, e depois deste episódio vou estar mesmo atento.

P.S.: Contei este episódio a uma pessoa que me disse que numa qualquer superfície o mesmo acontecia com os sacos de areia para gatos de 5 e 10 kg. Não comprovei :-P

© Bruno Silva | Powered by Wordpress