• RSS
  • Add To My MSN
  • Add To Windows Live
  • Add To My Yahoo
  • Add To Google

String “interning” mechanism in the .Net Micro Framework 

Posted by Paolo Patierno Sunday, February 22, 2015 10:59:12 AM
Rate this Content 0 Votes

Consider the following simple console application in C # ...

   1: static void Main(string[] args)
   2: {
   3:     string s1 = "Hello world";
   4:     string s2 = "Hello world";
   5:  
   6:     Console.WriteLine(s1.Equals(s2));
   7:     Console.WriteLine(ReferenceEquals(s1, s2));
   8:     Console.WriteLine(s1 == s2);
   9:  
  10:     string s3 = String.Intern(Console.ReadLine());
  11:  
  12:     Console.WriteLine(s1.Equals(s3));
  13:     Console.WriteLine(ReferenceEquals(s1, s3));
  14:     Console.WriteLine(s1 == s3);
  15:  
  16:     Console.ReadKey();
  17: }

who has the following output …

string_intern_net

As we know the Equals() method and the "==" operator check if the two strings contain the same value while having a different reference (s1 and s2), for which it is obvious the result "True". Why does the ReferenceEquals() provides "True" instead of "False" considering that the two references are different ?

Okay ! They are not different in reality !

The .Net Framework provides a mechanism of "string interning" and a pool who contains strings that have the same value and avoid unnecessarily memory allocation. For this reason, s1 and s2 are actually the same reference !

It 'obvious that, when a string is acquired from the outside it doesn’t happen and you need to explicitly ask the framework to search for the string acquired before the internal pool and possibly allocate a new one if it does not exist ... that is the goal of the String.Intern() method.

Let's try to run the same code (unless some changes) on the .Net Micro Framework ...

   1: static void Main(string[] args)
   2: {
   3:     string s1 = "Hello world";
   4:     string s2 = "Hello world";
   5:  
   6:     Console.WriteLine(s1.Equals(s2));
   7:     Console.WriteLine(ReferenceEquals(s1, s2));
   8:     Console.WriteLine(s1 == s2);
   9:  
  10:     string s3 = String.Intern(Console.ReadLine());
  11:  
  12:     Console.WriteLine(s1.Equals(s3));
  13:     Console.WriteLine(ReferenceEquals(s1, s3));
  14:     Console.WriteLine(s1 == s3);
  15:  
  16:     Console.ReadKey();
  17: }

with the following output …

string_intern_netmf

In this case the ReferenceEquals() confirms that the two reference are different in the first case but also using String.Intern() ... why ?

The reason is simple ... the .Net Micro Framework does not support the mechanism of "string interning" and does not provide an internal pool of strings and the answer is as always in the native implementation. Looking into the String.cs file, we find :

   1: public static String Intern(String str)
   2: {
   3:     // We don't support "interning" of strings. So simply return the string.
   4:     return str;
   5: }
   6:  
   7: public static String IsInterned(String str)
   8: {
   9:     // We don't support "interning" of strings. So simply return the string.
  10:     return str;
  11: }

An explicit comment tells us that this feature is not supported !

Regex portability between .Net and .Net Micro Framework … pay attention !! 

Posted by Paolo Patierno Saturday, February 14, 2015 11:53:19 AM
Rate this Content 0 Votes

Developing on all versions of the .Net Framework (full, compact and micro) I have always the portability problem and I avoid to use methods that are not available in one of three framework or using directives for precompilation.

It never happened a case where the method exists in all the frameworks but the parameters have a different meaning ... are even reversed !!

The method in question is the overload Regex.Split(String, String, RegexOptions) !

The signature is practically the same comparing the .Net Framework and .Net Micro Framework .... but with a significant difference in the first two parameters.

From the MSDN documentation of the .Net Framework we can read that the first parameter is the string to split while the second is the pattern to be applied.

 

01

Conversely, in the MSDN documentation of the .Net Micro Framework we can read that the first is the pattern and the second is the input string !!

 

02

To be sure that the error is not in the documentation, I searched the source code of the .Net Micro Framework that implement this method but unfortunately came the confirmation !

   1: /// <summary>
   2: /// Splits the input string at the positions defined by a specified regular expression pattern. Specified options modify the matching operation.
   3: /// </summary>
   4: /// <param name="pattern">The pattern to match against</param>
   5: /// <param name="split">The string to split</param>
   6: /// <param name="options">The options to utilize during matching</param>
   7: /// <returns>The result of splitting the input string against the pattern</returns>
   8: public static string[] Split(string pattern, string split, RegexOptions options)
   9: {
  10:     return new Regex(pattern, options).Split(split);
  11: }

Absolutely strange ... this time I decided to open an issue on the official website of the .Net Micro Framework on CodePlex !

Non standard Base64 encoding in the .Net Micro Framework 

Posted by Paolo Patierno Saturday, February 07, 2015 11:02:21 AM
Rate this Content 0 Votes

As we know, to be able to access to some Microsoft Azure services, there is the SAS (Shared Access Signature) Authentication by sending a token by which we get the rights to perform specific operations.

This token is obtained by building a string containing some information including the URI to access and the expiration time over which to calculate an HMAC (Hash Massage Authentication Code) with SHA256. The result of this hashing operation is encoded in Base64 and the result obtained is inserted in the token (Shared Access Signature) with an appropriate format.

The goal of this short post isn’t to describe the procedure for determining the token but to warn the user about the Base64 conversion functions provided by the .Net Micro Framework.

Performing my tests with a board FEZ Spider to connect to the Service Bus, I have found many times the condition of unauthorized access due to an incorrect token. By performing the same procedure on the PC, everything worked properly. How so ?

Initially I thought of a mistake in the signature (HMAC) calculation and only after I realized there was something wrong in the Base64 encoding.

I finally obtained a case of error following the signing represented through the following bytes:

   1: byte[] hmac = { 0x16, 0x01, 0x70, 0x76, 0xec, 0xc8, 0xdb, 0x01, 0xf0, 0x6a, 0x60, 0x9a, 0x89, 0x68, 0x6f, 0xef, 0x68, 0x9a, 0xad, 0x10, 0xe7, 0x92, 0x9b, 0xef, 0xfa, 0x10, 0x86, 0x24, 0xf1, 0x72, 0xa6, 0x69 };

If we try to Base64 encode the array of bytes above using the Convert.ToBase64String (hmac) method on PC, the result is as follows:

FgFwduzI2wHwamCaiWhv72iarRDnkpvv+hCGJPFypmk=

If we try to perform the same operation with the .Net Micro Framework, the encoding is as follows :

FgFwduzI2wHwamCaiWhv72iarRDnkpvv!hCGJPFypmk=

In red and bold, I highlighted the difference between the two encodings but ... what is the reason?

As always, the answer is in the native implementation of the .Net Micro Framework and this time in the Convert.cs file within which there are two different "alphabets" for Base64 encoding: the standard RFC4648 alphabet and a non-standard alphabet.

   1: /// <summary>
   2: /// Conversion array from 6 bit of value into base64 encoded character.
   3: /// </summary>
   4: static char[] s_rgchBase64EncodingDefault = new char[]
   5: {
   6: 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', /* 12 */
   7: 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', /* 24 */
   8: 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 36 */
   9: 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', /* 48 */
  10: 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 60 */
  11: '8', '9', '!', '*' /* 64 */
  12: };
  13:  
  14: static char[] s_rgchBase64EncodingRFC4648 = new char[]
  15: {
  16: 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', /* 12 */
  17: 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', /* 24 */
  18: 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 36 */
  19: 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', /* 48 */
  20: 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 60 */
  21: '8', '9', '+', '/' /* 64 */
  22: };
  23:  
  24: static char[] s_rgchBase64Encoding = s_rgchBase64EncodingDefault;

These two alphabets differ in the last two characters that are "+" and "/" in the first "!" and "*" in the second. Apparently the "!" is relative to Base64 encoding in regular expressions as "*" is relative to the same encoding in privacy-enhanced mail.

The code shows that the default alphabet (s_rgchBase64Encoding) that is kept here is not that standard !!

How can we fix the problem?

Fortunately, the Convert class provides the static property UseRFC4648Encoding that must be set to true to use the standard RFC4648 Base64 encoding.

My opinion is that it would be appropriate to reverse the logic so that the default encoding is the standard, and for this reason I have already opened an issue on the official website of the .Net Micro Framework on CodePlex.

What do you think about that ??

IoT per sviluppatori Microsoft 

Posted by Paolo Patierno Thursday, January 15, 2015 10:29:05 AM
Rate this Content 0 Votes

IoTMicrosoftPodcast

Una delle più grandi iniziative del 2014 è stata sicuramente la nascita di DotNetPodcast, podcast completamente in italiano e dedicato alle tecnologie Microsoft. Gli ospiti sono sempre di altissimo livello e ad inizio anno, ho avuto l’onore di poter registrare una puntata, completamente dedicata all’Internet of Things ed allo sviluppo di soluzioni IoT attraverso il .Net Micro Framework. Ringrazio Roberto Albano, Antonio Giglio e Massimo Bonanni per la fiducia !!

Nel corso del podcast, ho cercato di descrivere in maniera semplice cosa sia un sistema embedded e come siamo abituati a convivere con oggetti di questo tipo quotidianamente. Dalle “cose” si arriva all’Internet delle cose ed alla relativa integrazione con i servizi nel cloud. Per poter permettere a tutti gli sviluppatori .Net un approccio “friendly” a questo mondo, Microsoft offre il.Net Micro Framework per il quale abbiamo a disposizioni numerose board di sviluppo :Netduino (Secret Labs) e le board della famiglia FEZ (GHI Electronics). Nel corso della puntata, ho analizzato l’architettura con relativi vantaggi e svantaggi di questo framework e come sia possibile iniziare a sviluppare (in maniera gratuita a meno dell’acquisto dell’hardware) le proprie “cose” da collegare alla rete.

Curiosi ? Non vi resta che ascoltarmi !  (se vi va)

:-)

M2Mqtt su una Raspberry Pi con il progetto Mono 

Posted by Paolo Patierno Saturday, December 27, 2014 5:52:31 PM
Rate this Content 0 Votes

Un nuovo use case per la libreria M2Mqtt !! La sezione dei case studies sul sito ufficiale si è arricchita con un altro grande esempio !

Jon Gallant, parte del Microsoft IoT maker team, ha scritto un interessantissimo articolo relativamente alla sua “esperienza da maker” con una demo sull’utilizzo del protocollo MQTT su una Raspberry Pi. Jon ha deciso di non utilizzare le librerie native C/C++ ma il linguaggio C# e quindi la libreria M2Mqtt grazie al progetto Mono !

L’articolo descrive tutti i passi per mettere in piedi l’intera demo dall’hardware fino all’installazione di Mono sulla Raspberry Pi ed all’esecuzione della relativa applicazione.

E’ bello vedere un ulteriore esempio di utilizzo del client M2Mqtt…e questa volta in ambiente Linux !

Page 1 of 47 1 2 3 4 5 6 7 8 9 10 20 > >>