Monday, October 1, 2012

Git push error: RPC failed; result=55, HTTP code = 0

Today I had some problem pushing my data on a git repository.
The data was some MB and the error message when I did the push was

   fatal: The remote end hung up unexpectedly
   error: RPC failed; result=55, HTTP code = 0

If you get this error, it's because you are trying to push a large delta to the repository and your push buffer is not big as needed.

The solution is to increase your buffer size with this command:

   git config http.postBuffer 1024000

This will add a line in your config file with the specified value.
Set the value to what you need.
The http.postBuffer configuration value is exactly the maximum size in bytes of the buffer used by smart HTTP transports when POSTing data to the remote system (source).

EDIT: 2014/02/06
An user (Matej Sychra) in a commet report you need a value bigger than 1024000 for lager repository.
Thanks Matej!

Tuesday, July 24, 2012

Automapper upper and lower case properties mapping

Yesterday I face some sort of common problem: mapping an class to another one (a DTO).
The first class was a generated entity using Entity Framework 4.
The database is a legacy one, and of course untouchable and the name of the columns are are all upper case.
To map these entities to a DTO class, I'm using best tool for .NET on the way: I'm talking about AutoMapper of course.
As you probably know, AutoMapper is a convention-based object-object mapping library.
In a basic usage, AutoMapper maps your property automatically to another one, if the property have the same name.
In my case this convection (the default one) doesn't work because of the upper-case properties, different by the properties of the DTO.

The solution.

AutoMapper, as said is convention based, so you have simply to say to it, to consider one said of the mapping with upper-case property.

How to do it?
First of all write your Naming Convention class:
public class UppercaseNamingConvenction : INamingConvention
{
   private static readonly Regex _splittingExpression
         = new Regex("(\\p{Lu}0-9]+)");

   #region Implementation of INamingConvention

   public Regex SplittingExpression
   {
      get { return _splittingExpression; }
   }

   public string SeparatorCharacter
   {
      get { return string.Empty; }
   }

   #endregion
} 
As you can see, we use a splitting regular expression with a upper case specification.

The next is to define an Automapper profile to specify a different configuration usage.
Write the code below where you configure your application at startup.


Mapper.CreateProfile("first_profile"
   , expression =>
   {
      expression.SourceMemberNamingConvention
         = new UppercaseNamingConvenction();
   });

Mapper.CreateProfile("second_profile"
   , expression =>
   {
      expression.SourceMemberNamingConvention
         = new UppercaseNamingConvenction();
   });

So you will have two profiles: "first_profile" and "second_profile".
To use this configuration, simple specific the profile when you define a mapping strategy:

Mapper.CreateMap<DtoClass, MyDbEntity>().WithProfile("first_profile");

Of course the strategy is the same if you have lower case properties: you have only to change the regular expression.

Have a nice mapping ;)

Saturday, July 7, 2012

Android - Mobile clouds @ Exchange program seminars on cloud computing


Wednesday 07/07/2012 I and Emanuele Palazzetticonducted a workshop in "Università degli studi di Perugia, dipartimento di Matematica/Informatica".

Was a long and funny day and this workshop, was one of the six for the "Exchange programme summer 2012",  between University of Perugia (IT) and Hong Kong Baptist University (HK).
Thanks to all the italy and hong kong studets was there, thanks to Professor Alfredo Milani and Valentina Franzoni.

The link of the page of the cloud computing events is here.

In the second part of the workshop, we did a full android application!
This application is a simple browser, with some nice features like a "Splash screen" and "Bookmarks save/delete" in a SQLite database.

Here the abstract of the seminar.
You can see the slide of first part here.
You can download the project resource (installation guide, a source tarball and the images) here.
Here you can find the full source code of the project on github to make your own fork.

I hope all the students (and professors :-) ) had fun building this app from scratch.

See you next seminar!

Friday, May 11, 2012

Videogiocare nell'universo FLOSS - i migliori videogame free e open source - le slide..


Sono online le slide del mio intervento all'IPSIA FLOSS 2011, dal titolo "Videogiocare nell'universo FLOSS".
Con l'occasione mi è stato fatto onore di una maglietta con su scritto "I videogiochi mi hanno rovinato la vita: per fortuna ne avevo altre 2", con questa immagine stampata sopra:

Gli argomenti trattati sono ovviamente i videogiochi, e cosa offre il mondo open source, e in particolare i sistemi GNU/Linux, oggi.

Buona visione =)

Tuesday, May 8, 2012

Android Error generating final archive: Debug Certificate expired on ..

If you are trying to build your android application using Eclipse ad you are getting an error like "Error generating final archive: Debug Certificate expired on dd/MM/yyyy" is because your signing debug certificate was created more than one year ago: the certificate auto-expires after 365 days.

The solution is to delete your debug.keystore in your android directory.

The exact location is  ~/.android/debug.keystore on Linux and Mac OS X and  %USERPROFILE%/.android on Windows.

After deleted it, the Eclipse plugin will generate a new certificate when you next try to build a debug package.

You may need first to clean the project.

More information about application signing here.

Happy coding =)

Monday, May 7, 2012

Android Workshop GTUG - Sabato 19 Maggio

Il Perugia GTUG con la collaborazione di Evonove Srl organizza un workshop di 4 ore finalizzato a fornire ai partecipanti gli strumenti di base per avvicinarsi alla programmazione di applicazioni mobili su piattaforma Android.

Il workshop si terrà Sabato 19 Maggio alle ore 9:00 nella nuova sede del coworking space di Evonove a Magione, situato al piano superiore dell'edificio sede dell'esposizione di Mobili Veracchi, a fianco del Mercatone UNO.
La partecipazione è gratuita previa registrazione all'indirizzo http://android-workshop.eventbrite.com e limitata a 6 partecipanti che verranno seguiti dai 2 tutor Michele Lepri ed Emanuele Palazzettisviluppatori freelance.

Per poter seguire le attività del workshop tutti i partecipanti dovranno avere a disposizione un laptop appositamente configurato secondo le linee guida presenti al seguente indirizzo: http://goo.gl/vEEXS.

Per qualsiasi richiesta di informazioni potrete contattare gli organizzatori in mailing list (http://groups.google.com/group/perugia-gtug) oppure all'indirizzo email pippi@gtugs.org.

Ci vediamo Sabato 19 ;)

Link originale.

Wednesday, April 25, 2012

ASP.NET MVC: use integer array as parameter or as property of a model

How many time, in your ASP.NET MVC application do you need to use an array of integer or other type as parameter of an action, or likely, as property in your model class?
A lot, I know..

By default is not possible, at least in ASP.MVC 2.

One example of possible use is a list of checkboxs with each one, as value, an identifier from some table on the database.
Iin this case, when you post your data, with a web debugger (like firebug) or a sniffer, you will see values like these:
... &myFieldName=101&myFieldName=322&myFieldName=112&myFieldName=316&myFieldName=109& ...

If you try to get the value declaring myFieldName as string , you will see this value:
"101,322,112,316,109"

So you can image what you need to do..

But we can solve it in a elegant clean and reusable way, changing the default behaviour: we have to write a model binder, like in this class below.


public class IntegerArrayModelBinder : IModelBinder
{
   /// <summary>
   /// Char used for splitting
   /// </summary>
   private const char CHAR_TO_SPLIT = ',';

   private static readonly ILog _log
                  = LogManager.GetLogger(typeof(IntegerArrayModelBinder));

   #region Implementation of IModelBinder

   /// <summary>
   /// Binds the model to a value by using the specified controller
   /// context and binding context.
   /// </summary>
   /// <returns>
   /// The bound value.
   /// </returns>
   /// <param name="controllerContext">The controller context.</param>
   /// <param name="bindingContext">The binding context.</param>
   public object BindModel(ControllerContext controllerContext,
                           ModelBindingContext bindingContext)
   {
      if (bindingContext == null)
      {
         throw new ArgumentNullException("bindingContext");
      }
      ValueProviderResult valueProviderResult
           = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

      if (_log.IsDebugEnabled)
      {
         _log.DebugFormat(
            "ModelName = {0}, valueProviderResult = {1}" +
            ", AttemptedValue = {2}, RawValue = {3}"
            , bindingContext.ModelName
            , valueProviderResult
            , valueProviderResult == null
                    ? null : valueProviderResult.AttemptedValue
            , valueProviderResult == null
                    ? null : valueProviderResult.RawValue
            );
      }

      if (valueProviderResult == null)
      {
         return new int[0];
      }
      string attemptedValue = valueProviderResult.AttemptedValue;
      if (string.IsNullOrEmpty(attemptedValue))
      {
         return new int[0];
      }

      var integers = attemptedValue.Split(new char[] { CHAR_TO_SPLIT }
                                  , StringSplitOptions.RemoveEmptyEntries);
      var list = new List<int>(integers.Length);

      foreach (string integer in integers)
      {
         int tmp;
         //this will use the NumberFormatInfo.CurrentInfo
         if (int.TryParse(integer, out tmp))
         {
            list.Add(tmp);
         }
         else
         {
            if (_log.IsWarnEnabled)
            {
               _log.WarnFormat("Unable to convert {0} to an integer"
                               , integer);
            }
         }
      }

      if (_log.IsDebugEnabled)
      {
         _log.DebugFormat("Result = {0}", list.Join("@"));
      }

      return list.ToArray();
   }

   #endregion
}

Warning: this class is using log4net logging library for debug logging: feel free to remove all the reference to it.
The char used as splitter is the ',' but you can change it.

Finally you have to register it in your Global.asax.cs .

   protected void Application_Start()
   {
      /* other code */

      ModelBinders.Binders.Add(typeof(int[]), new IntegerArrayModelBinder());
   }

Happy binding!

Friday, April 20, 2012

ASP.NET WebForm System.InvalidOperationException on postback: Operation is not valid due to the current state of the object.

If on a post-back in a WebForm of an ASP.NET application you get this error:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
And the stack trace is:
in System.Web.HttpRequest.FillInFormCollection()
in System.Web.HttpRequest.get_Form()
in System.Web.HttpRequest.get_HasForm()
in System.Web.UI.Page.GetCollectionBasedOnMethod(Boolean dontReturnNull)
in System.Web.UI.Page.DeterminePostBackMode()
in System.Web.UI.Page.ProcessRequestMain(
                           Boolean includeStagesBeforeAsyncPoint,
                           Boolean includeStagesAfterAsyncPoint)

You are trying to send a lot of values (TextBox, CheckBox, etc..) to the server.

The solution are two:
  1. refactor your page (not always easily possible);
  2. change the security settings;
Why security settings? Because the exception is caused by an internal security check done by the framework on the number of the posted values.
So you have to increase that limit on your web.config file, adding this key:

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
</appSettings>

Of course change this values at your needs.

 If your Exception occur when your send JSON with JavaScript, you have to add this other key to the web.config file:

<appSettings>
    <add key="aspnet:MaxHttpCollectionKeys" value="2000" />
</appSettings>

Again, change this value at your needs.

Happy exception handling! ;-)

Thursday, April 12, 2012

Asp.NET data binding: Object does not match target type.

Every day is a new adventure .. Today I face this "funny" behaviour of the ASP.NET "data binding".

I'm working on ASP.NET webform application, and a piece of this application must automatically generate some documents, nearly all PDF.
The documents are all heterogeneous, and in an object oriented way, I decided to implement a interface on each class able to generate a document.

The interface IDocumentoSemplice is pretty trivial and have only few properties.



What I like to do, is gather all possible documents for a user, and show them in a GridView.
The documents are loaded in a service class and then bounded to the GridView for the "DataBind".
The columns in the page are nearly all BoundField.

   <asp:boundfield datafield="DataCompilazione" dataformatstring="{0:d}"  
                   headertext="Data Compilazione">
   </asp:boundfield>

All seems to be great, but when I start the page, this exception pop up: "Object does not match target type."

I check and recheck the code, but cannot find anything wrong.
Finally I googled a bit for this problem, and what I found is pretty funny: the "DataBind" (at least the GridView one) need all the data-bounded objects are to be of the same type.

The solution was pretty simple: convert all the bounded field in template one:

   <asp:TemplateField>
      <ItemTemplate>
         <%# Server.HtmlEncode(((IDocumentoSemplice)Container.DataItem)
                               .DataCompilazione.ToShortDateString())%>
      </ItemTemplate>
   </asp:TemplateField>



The problem seem to be caused by some internal classes used for the reflection, needed to get the properties value at runtime.


Happy "DataBind" ...

Tuesday, March 27, 2012

NetBeans 7.0 and 7.1 UML plugin

If you are using NetBeans 7.0 or 7.1, you probably can't find your UML plugin any more in the default repository.

From what I can read on the net, the team is working on the plugin rewriting it, and this will take a while.


Semi-broken solution

There is another way to install it, but beware, the plugin will be semi-broken, so jump down to another solution if you like to generate a pretty UML diagram from your code:
  1. by the menu navigate to Tools -> Plugins;
  2. select the "Settings" tab;
  3. click the "Add" button;
  4. as URL copy the following into the textbox:
    http://dlc.sun.com.edgesuite.net/netbeans/updates/6.9/uc/m1/dev/catalog.xml
Now on the tab "Available Plugins" there should be UML in category UML.

The problems are:
  • "reverse engineering" command seem to work but you can't open the files;
  • you can write a class diagram and work on it, but when you open your project next time you will unable to open the diagram again.
So all you can do is work on a temporary diagram, if you need only it.


Another solution

You can use yWorks UML Doclet community edition.
This solution will only let you generate a pretty UML diagram from your code.

  1. Download the library from here;
  2. right click on your java project in project explorer within NetBeans;
  3. click on "Properties";
  4. select  Build => Documenting;
  5. on "Additional Javadoc Options" textbox paste the following (beware, I'm under windows):
    -docletpath "<yworks-uml-doclet-path>\lib\ydoc.jar" -resourcepath "<yworks-uml-doclet-path>\resources" -doclet ydoc.doclets.YStandard -umlautogen

    Where <yworks-uml-doclet-path> is the path of the yworks-uml-doclet folder.
    In my case <yid> is:
    E:\Users\retek\dev\lib\java\yworks-uml-doclet\yworks-uml-doclet-3.0_01-jdk1.5
  6. click "OK";
  7. right click on your java project in project explorer within NetBeans;
  8. click Generate Javadoc;
Now, within your Javadoc you will have a very nice UML driagram for your classes.

Thanks to Matthew W. Johnson for this solution.

Tuesday, March 6, 2012

Javascript: variable_name is not defined

In Javascript, if your're are using a variable or a property and what you get is an error like "variable_name is not defined".
The message is pretty clear, but what is the best way to check and handle it?

There are some, but the best is:

   if (typeof my_variable === "undefined") {
      alert("my_variable is undefined");
   }

There are some others way, but they could have some problems, for example:

   if (my_variable === undefined) {
      alert("my_variable is undefined");
   }
This one doesn't work if in your scope is defined a variable called undefined.
This way also return true if my_variable is null.

Happy scripting =)

Thursday, February 16, 2012

Primo evento Perugia GTUG


Venerdì 9 Marzo 2012 alle ore 18:00 si terrà a Bastia Umbra il primo evento organizzato dal Perugia GTUG (Google Technology User Group), durante il quale verrà presentato ufficialmente lo user group e saranno illustrate e discusse le prossime iniziative.
Durante l’evento ci sarà anche spazio per due brevi interventi tecnici introduttivi su Android e Google App Engine.
 

Mappa
http://bit.ly/bocciofila

Programma
Ore 18.00 - Presentazione del GTUG Perugia
Ore 18.20 - Google App Engine, una piattaforma su cloud (Massimiliano Pippi)
Ore 18.40 - Scopriamo Android (Luca Morettoni)
Ore 19.00 - Free drink & Open discussion

Modulo d'iscrizione:
Ci vediamo venerdì 9 =)

Wednesday, February 15, 2012

NHibermate 3.2: mapping by code complete guide

Adam Bar wrote a list of posts on his blog about the NHibernate mapping by code, also known as loquacious mapping.
So far, this is the only complete guide on the web about the new xml-less mapping.
A great job has been done with many comparisons between xml and FluentNHibernate mapping.

The summary is here:
http://notherdev.blogspot.com/2012/02/nhibernates-mapping-by-code-summary.html

Have a nice read :)

Monday, January 23, 2012

NHibernate proxy of incorrect type exception: "PropertyAccessException Invalid Cast (check your mapping for property type mismatches)"

Are you facing this exception?

NHibernate.PropertyAccessException : Invalid Cast (check your mapping for property type mismatches); setter of MyEntity ----> System.InvalidCastException : Unable to cast object of type 'MyOtherEntityProxy' to type 'AnotherEntity'.

Looking on google, I saw that other programmers have this type of problem.

This article can help you if you are using Ninject and uNhAddIns.NinjectAdapters for entity injection in NHibernate.

If you are using the "NinjectAdapter" assembly, you need to bind the IProxyFactory interface to a class, for example to the default provided with NHibernate, DefaultProxyFactory, if is good for you.
My problem was the definition of this bind in a Ninject kernel module, copied from somewhere on the net or from a book, I can't remember.
   Bind<NHibernate.Proxy.IProxyFactory>()
      .To<NHibernate.Proxy.DefaultProxyFactory>()
      .InSingletonScope(); // <= here the problem


Declaring this bind in singleton scope is not good because the instance will be shared between NHibernate entities metadata classes: so you will get always the first ProxyFactory instance created and you will receive an error like the one above at runtime when you need a proxy classes of a type different from the first one created.

Was really a pain and take a lot of time to find out the problem as you can image, and the solution is to declare the bind InTransientScope(), of course.

   Bind<NHibernate.Proxy.IProxyFactory>()
      .To<NHibernate.Proxy.DefaultProxyFactory>()
      .InTransientScope(); // <= problem fixed

Here the documentation about the object scopes in Ninject.

Doing a similar mistake, you could have the same problem with another dependency injection library like Sprint.Net or CastleWindsor, of course.

Hope it helps :)

Wednesday, January 18, 2012

Antivirus real time gratis per Windows: ClamWin + ClamSentinel

L'utilizzo dell'antivirus in questi ultimi anni è diventato uno strumento obbligatorio, sopratutto in ambiente Windows.
Perché spendere dei soldi per acquistare un antivirus quando sulla rete possiamo trovare dei software interamente gratis e di buona qualità!? La soluzione che andiamo a descrivere è l'unione di due programmi open source: ClamWin e ClamSentinel. Questi due programmi sono progetti di software libero ed entrambi fanno capo al progetto Clam AntiVirus.

- ClamWin fornisce un'interfaccia grafica per il motore antivirus ClamAV ma non supporta la scansione del sistema in tempo reale. Per colmare questa lacuna andremo ad utilizzare un altro software.
Disponibile al seguente link: http://sourceforge.net/projects/clamwin/

- ClamSentinel è un programma che monitora costantemente ogni modifica ai propri file e ne controlla il contenuto alla ricerca di virus usando ClamWin.
Disponibile al seguente link: http://sourceforge.net/projects/clamsentinel/

Qualcuno potrebbe obiettare che esistano già antivirus commerciali in versione gratuita.
Sì è vero, ma Clam Antivirus non è una seconda scelta né tanto meno una versione ridotta: è il miglior software disponibile in maniera totalmente libera, gratuita e senza pubblicità.

Wednesday, January 11, 2012

Efficient and scalable select of a random record in PostgreSQL


This is a code snippet for the select of a random record in a efficient and scalable way when using PostgreSQL:

   SELECT * FROM table_name
   LIMIT 1
   OFFSET (SELECT Random() * Count(*) FROM table_name);

According with the manual, the Random() function return a random value in the range 0.0 <= x < 1.0 .
So the effect of the expression (Random() * Count(*)) is to return a value between 0 and Count(*): we can use this value as offset to skip a random values of records.

This work in PostgreSQL 8.* and 9.*.

This solution required two queries, but if you have many records, is more efficient than this other one :

   SELECT * FROM table_name
   ORDER BY Random()
   LIMIT 1;

In this solution the Random() function is called for each row, so with many records it could be inefficient in term of execution time and memory usage.

Friday, January 6, 2012

Ubuntu GNU/Linux: configurare Samba per condividere cartelle

Esempio di condivisione cartelle con Samba su Ubuntu Linux: 

Cartelle condivise:
backup (accessibile da tutti gli utenti)
db (accessibile da tutti gli utenti)
scambio (accessibile da tutti gli utenti)
utente.1 (accessibile solo da utente1)
utente.2 (accessibile solo da utente2)

Creazione utenti:
sudo useradd -c “admin condiviso” -m -g users -p 123456789 super
nome completo = admin condiviso
gruppo di appartenenza = users
password = 123456789
username = super
sudo smbpasswd -a super

sudo useradd -c “utente uno” -m -g users -p 1234567890 utente1
nome completo = utente uno
gruppo di appartenenza = users
password = 1234567890
username = utente1
sudo smbpasswd -a utente1

sudo useradd -c “utente due” -m -g users -p 12345678 utente2
nome completo = utente due
gruppo di appartenenza = users
password = 12345678
username = utente2
sudo smbpasswd -a utente2

Creazione cartelle:
sudo mkdir /dati
sudo mkdir -m 777 /dati/backup
sudo mkdir -m 777 /dati/db
sudo mkdir /dati/utenti
sudo mkdir -m 777 /dati/utenti/utente.1
sudo mkdir -m 777 /dati/utenti/utente.2
sudo mkdir -m 777 /dati/utenti/scambio

Editare il file /etc/samba/smb.conf:
sudo vi /etc/samba/smb.conf
[global]
workgroup = workgroup
netbios name = serer
server string  = server_dati
security = user
encrypt passwords = yes
browsable = yes

[backup]
path = /dati/backup
comment = cartella_backup
read only = no
valid users = super utente1 utente2

[db]
path = /dati/db
comment = cartella_db
read only = no
valid users = super utente1 utente2

[scambio]
path = /dati/utenti/scambio
comment = cartella_scambio
read only = no
valid users = super utente1 utente2

[utente.1]
path = /dati/utenti/utente.1
comment = cartella_utente1
read only = no
valid users = super utente1

[utente.2]
path = /dati/utenti/utente.2
comment = cartella_utente2
read only = no
valid users = super utente2

Assicurati che tutto sia OK digitando:
sudo testparm

Riavviare servizio samba:
sudo /etc/init.d/smbd restart 

Wednesday, January 4, 2012

NHibernate mapping by code a sequence generator

How to map an identifier when you want to use a sequence generator, like the one used by PosrgreSQL ?
Here is an example in the loquacious way using the ClassMapping<T> base class, and, of course, the MapperModel:

   public sealed class MyEntityMap : ClassMapping<MyEntity>
   {
      public MyEntityMap ()
      {
         Table("my_table");
         Id(x => x.Id,
            a =>
            {
               a.Column("my_id");
               a.Generator(Generators.Sequence, g => g.Params(new
               {
                  sequence = "my_sequence_generator"
               }));
            });
      }
   }

Happy mapping ^^