Sunday, January 9, 2011

Wedding Reception Program Outline

VB.NET VB for Dummies: The Serialization - Part 2

This post is a continuation of previous post serialization.

In particular we will see that the SOAP and JSON serialization.

Serialization SOAP SOAP serialization is committed to the SoapFormatter System.Runtime.Serialization.Formatters.Soap contained in the namespace in the library of the same name. The SOAP formatter

goes back to the earliest versions of the framework and, unfortunately, from a certain point, even though it was declared obsolete, it was not brought forward in the development and does not support certain types of data very much used in the world. NET such as generics and nullable.

For this reason, we can not serialize in SOAP format (using the SoapFormatter) our bill (see previous post) as this has a property of type List (Of DettagliFattura) (generic).

JSON serialization format JSON serialization (more info here ) is a textual format very popular in AJAX applications. Entry is a way to serialize complex objects even with a very compact size and easy to interoperate with JavaScript, therefore, well suited for scenarios partoicolarmente AJAX-style web.

JSON serialization can be done using the class DataContractJsonSerializer that framework 4.0 is contained in the namespace System.Runtime.Serialization.Json all’interno dell’omonimo assembly.

Fate attenzione perchè, se state sviluppando per il framework 3.5 (prima di questo la classe DataContractJsonSerialization non era presente), trovate la classe nello stesso namespace ma l’assembly è System.ServiceModel.Web.

La classe DataContractJsonSerializer prevede, tra i vari metodi, WriteObject e ReadObject che permettono , rispettivamente, di serializzare e deserializzare un’oggetto in formato JSON.

Entrambi i metodi sfruttano uno stream per serializzare l’oggetto. In base alle nostre esigenze tale stream potrebbe essere in memoria (come nell’esempio riportato in seguito), su file o su un canale web (ad esempio come response to a request from a remote client).

methods for serialization and deserialization of the object are Invoice:

  1. Public Shared Function SerializzaJSON (ByVal bill As Invoice ) As String
  2. If bill Is Nothing Then Throw New ArgumentNullException ( "Bill" )
  3.      Dim strJSON As String = Nothing
  4.      Dim serializer = New DataContractJsonSerializer ( GetType ( Fattura ))
  5.      Using memStream = New MemoryStream ()
  6.          serializer .WriteObject(memStream, fattura)
  7.         strJSON = Encoding.Default.GetString( memStream .ToArray())
  8.      End Using
  9.      Return strJSON
  10. End Function
  11.  
  12. Public Shared Function DeserializzaJSON( ByVal As strFattura String) As Invoice
  13. Dim retObj As Invoice = Nothing
  14. & # 160; Dim serializer = New DataContractJsonSerializer ( GetType ( Invoice )) &
  15. # 160; Using memStream = New MemoryStream (Encoding.Default.GetBytes (strFattura))
  16. retObj = CType (serializer . ReadObject (memStream) Invoice )
  17. End Using Return
  18. retObj
  19. End Function

The result is as follows:

image

We observe that, in the examples, we used the default encoding for strings. Evidently, if necessary, the encoding may be the one we want.

If our class (as in Bill) is composed of objects. NET serializable, we can immediately use the JSON serialization.

Alternatively, we can decorate our class (and all those that may be used as a property) with the Serializable attribute or the attribute DataContract.

In the first case it is enough to decorate the sun and JSON serialization classes will have the properties expressed by the name of the attribute that is encapsulated by private property. In the case of property definite in modo compatto (come accade nella Fattura) il compilatore crea, dietro le quinte un attributo per ogni proprietà con lo stesso nome della proprietà a cui viene anteposto il carattere “_”. In questo caso il JSON risultante vedrà le proprietà espresse con il nome della proprietà preceduta da “_”.

Nel caso dell’attributo DataContract, invece, è necessario decorare anche ogni proprietà con l’attributo DataMember (se una proprietà non viene decorata con DataMember, questa non finisce nella serializzazione).

L’attributo DataMember permette di rinominare la proprietà all’interno del JSON risultante:

  1. \u0026lt; DataMember (Name: = "numeroDocumento" )>
  2. Public Property NumeroDocumento As String

In this case, the properties, the ' inside of the JSON, will be called "numeroDocumento" and not "NumeroDocumento.

using DataContract and DataMember we can intervene in the resulting JSON in order to customize the results to our liking (especially useful when we are given the path and we must re-create the class).

Serializzazion custom

Just a hint at the possibility of creating a custom serialization of objects.

To do this, the framework provides us with the interface that has two IFormatter Serialize and Deserialize methods that we have to redefine our logic by implementing the serialization / deserialization:

An example might be:

  1. Imports System.Runtime.Serialization
  2. Public Class MioSerializzatore
  3. Implements IFormatter
  4.  
  5.      Public Property Binder As System.Runtime.Serialization. SerializationBinder Implements System.Runtime.Serialization. IFormatter .Binder
  6.          Get
  7.  
  8.          End Get
  9.          Set ( ByVal value As System.Runtime.Serialization. SerializationBinder )
  10.  
  11.          End Set
  12.      End Property
  13.  
  14.      Public Property Context As System.Runtime.Serialization. StreamingContext Implements System.Runtime.Serialization. IFormatter .Context
  15.          Get
  16.  
  17.          End Get
  18.          Set ( ByVal value As System.Runtime.Serialization. StreamingContext )
  19.  
  20.          End Set
  21.      End Property
  22.  
  23.      Public Function Deserialize( ByVal serializationStream As System.IO. Stream ) As Object Implements System.Runtime.Serialization. IFormatter . Deserialize
  24. 'Here comes the logic of deserialization
  25. End Function
  26. Public Sub Serialize (ByVal serializationStream As System.IO. Stream , ByVal graph As Object ) Implements System.Runtime.Serialization. IFormatter .Serialize
  27.          ' qui ci va la logica di serializzazione
  28.      End Sub
  29.  
  30.      Public Property SurrogateSelector As System.Runtime.Serialization. ISurrogateSelector Implements System.Runtime.Serialization. IFormatter .SurrogateSelector
  31.          Get
  32.  
  33.          End Get
  34.          Set ( ByVal value As System.Runtime.Serialization. ISurrogateSelector )
  35. End September
  36. End Property End
  37. Class
Technorati tags: serialization, serialization , , xml, soap , ,

Saturday, January 8, 2011

Wrestling Singlets For Baby

WP7 Tip: Changing the background of a control based on the theme

Following a thread appeared on forum for the development in Microsoft Windows phone I will return an implementation of a converter that allows you to change the background of a control in XAML based on the active theme.

Getting Started "steal" the tip of the evil genius on the way to determine the active theme (link ) and convert it to VB.NET. In particular, we create a shared method (but should be a property shared well) in our application class App:

  1. Public Shared Function GetCurrentTheme() As Theme
  2.      Dim bgc = App.Current.Resources( "PhoneBackgroundColor" ).ToString()
  3.      If bgc = "#FF000000" Then
  4.          Return Theme .Dark
  5. Else
  6. Return Theme .
  7. Light
  8. End If End
  9. Function

Theme enumeration is defined as follows:

  1. Public Enum Theme
  2. Dark
  3. Light
  4. End Enum

At this point we can create our conveter:

  1. Imports System.Windows.Data
  2. Imports System.Windows.Media
  3. Public Class ThemeColorConverter
  4. Implements IValueConverter
  5. Private Function GetColorFromName( ByVal strColor As String ) As Color ?
  6.          Dim retColor As Color ? = Nothing
  7.          Try
  8.              Dim propColor = GetType ( Colors ).GetProperty(strColor)
  9.              If propColor IsNot Nothing Then
  10.                  Dim value = propColor .GetValue( Nothing , Nothing )
  11.                  If value IsNot Nothing Then
  12.                     retColor = CType (value, Color )
  13.                  End If
  14.              End If
  15.          Catch ex As Exception
  16.             retColor = Nothing
  17.          End Try
  18.          Return retColor
  19.      End Function
  20.  
  21.      Private Function GetColorFromRGB( ByVal strColor As String ) As Color ?
  22.          Dim retColor As Color ? = Nothing
  23.         strColor = strColor .Replace( "#" , "" )
  24.          Dim a As Byte = 255
  25.          Dim r As Byte = 255
  26.          Dim g As Byte = 255
  27.          Dim b As Byte = 255
  28.          Dim start = 0
  29.          If strColor .Length = 6 Or strColor .Length = 8 Then
  30.              If strColor .Length = 8 Then
  31.                 a = Byte .Parse( strColor .Substring(0, 2), System.Globalization. NumberStyles .HexNumber)
  32.                 start = 2
  33.              End If
  34.             r = Byte .Parse( strColor .Substring(start, 2), System.Globalization. NumberStyles .HexNumber)
  35.             g Bytes = . Parse ( strColor . Substring (start + 2, 2), System.Globalization. NumberStyles . HexNumber)
  36. & # 160; b = Byte . Parse ( strColor . Substring (start + 4, 2) , System.Globalization. NumberStyles . HexNumber)
  37. & # 160; retColor = Color .FromArgb(a, r, g, b)
  38.          End If
  39.          Return retColor
  40.      End Function
  41.  
  42.      Private Function GetColor( ByVal strColor As String ) As Color
  43.          Dim retColor As Color
  44.  
  45.          Dim tmpColor = GetColorFromName(strColor)
  46.          If Not tmpColor .HasValue Then
  47.             tmpColor = GetColorFromRGB(strColor)
  48.              If tmpColor .HasValue Then
  49.                 retColor = tmpColor .Value
  50.              End If
  51.          Else
  52.             retColor = tmpColor .Value
  53.          End If
  54.  
  55.          Return retColor
  56.      End Function
  57.  
  58.      Public Function Convert( ByVal value As Object ,
  59.                              ByVal targetType As System. Type ,
  60.                              ByVal parameter As Object ,
  61.                              ByVal culture As System.Globalization. CultureInfo ) As Object Implements System.Windows.Data. IValueConverter .Convert
  62.          If value IsNot Nothing Then
  63.              Dim brush As SolidColorBrush = Nothing
  64. ,.. Dim values \u200b\u200b= value ToString () Split ( " If
  65. App .GetCurrentTheme() = Theme .Light Then
  66.                     brush = New SolidColorBrush (GetColor(values(0)))                  Else
  67.                     brush = New SolidColorBrush
  68. (GetColor(values(1)))
  69.                  End
  70. If              End
  71. If              Return
  72. brush
  73.          Else
  74.             
  75. Return Nothing
  76.          End
  77. If      End
  78. Function  
  79.     
  80. Public Function ConvertBack( ByVal
  81. value
  82. As
  83. Object ,                                  ByVal targetType As System. Type ,
  84.                                 
  85. ByVal parameter As Object ,
  86.                                 
  87. ByVal culture As System.Globalization. CultureInfo ) As
  88. Object Implements System.Windows.Data. IValueConverter .ConvertBack          Throw New NotImplementedException ()
  89.     
  90. End Function End
  91. Class
  92. La funzione GetColor ci consente di obtain a Color object from a string in the following formats AARRGGBB #, # RRGGBB or "color name" (as that may be one of the possible colors of the class Colors ).
  93. The Convert method of our converter retrieves the argument value, which by convention should be a string with the following format:
light color theme can be used directly in binding within the XAML.

To do this you simply reference the appropriate namespace:

xmlns:

my = "clr-namespace: WP7ThemeBackground"

    Insert the converter into the resources of 'application or page
  1. \u0026lt; phone
:
PhoneApplicationPage.Resources

>

  1. \u0026lt; my : ThemeColorConverter x :
  2. Key = "TCC"> \u0026lt;/ my : ThemeColorConverter > \u0026lt;/ phone : PhoneApplicationPage.Resources >
  3. And finally, put the drive in with the background binding of control desired: \u0026lt; Grid
x
:

Name = "LayoutRoot"
  1. Background = "{Binding Converter = { StaticResource TCC} , Source = Red \u0026lt; phone : phone application page x
:
Class

= "WP7ThemeBackground.MainPage"

xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  1. ; xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
  2. xmlns: phone = "clr-namespace: Microsoft.Phone.Controls; Microsoft.Phone assembly ="
  3. ; xmlns:
  4. shell = "clr-namespace: Microsoft.Phone.Shell; Microsoft.Phone assembly =" & # 160; xmlns:
  5. d = "http://schemas.microsoft.com/expression/blend/2008"     xmlns :
  6. mc ="http://schemas.openxmlformats.org/markup-compatibility/2006"     xmlns :
  7. my ="clr-namespace:WP7ThemeBackground"     mc :
  8. Ignorable ="d" d : DesignWidth
  9. ="480" d : design height = "768"
  10. FontFamily = "{ StaticResource phone FontFamily normal} " font size = "{ StaticResource phone font size normal} "
  11. Foreground = "{ StaticResource PhoneForegroundBrush} "
  12.    
  13. SupportedOrientations ="Portrait" Orientation ="Portrait"     shell
  14. : SystemTray.IsVisible ="True" >      <
  15. phone : PhoneApplicationPage.Resources >
  16.         
  17. < my : ThemeColorConverter
  18. x : Key ="TCC"></ my : ThemeColorConverter
  19. >      </ phone : PhoneApplicationPage.Resources >      <!--LayoutRoot is the root grid where all page content is placed-->      <
  20. Grid x : Name ="LayoutRoot" Background ="{
  21. Binding Converter ={
  22. StaticResource TCC} , Source =Red AA00FF00} "> \u0026lt; Grid. RowDefinitions > & # 160; \u0026lt; RowDefinition Height = "Auto" />
  23. <
  24. RowDefinition Height ="*"/>         
  25. </ Grid.RowDefinitions >           
  26. <!--TitlePanel contains the name of the application and page title--> \u0026lt; StackPanel
  27. x
  28. : Name = "title panel" Grid.Row
  29. = "0"
  30. Margin
  31. = "12,17,0,28> & # 160;
  32. \u0026lt; TextBlock x : Name = "application title" text = "My Application" Style = "{ StaticResource
  33. phone text normal style}
  34. "/> & # 160; \u0026lt; TextBlock x : name = "page title" text = "pagename" Margin = "9, -7,0,0"
  35. Style = "{
  36. StaticResource PhoneTextTitle1Style } "/> \u0026lt;/ StackPanel > \u0026lt;- content panel - place additional content here -> \u0026lt; Grid
  37. x
  38. : Name = "content panel" Grid.Row
  39. = "1"
  40. Margin
  41. = "12,0,12,0"> \u0026lt;/
  42. Grid>
  43. \u0026lt;/ Grid> \u0026lt;/ phone: PhoneApplicationPage >
  44. Tag on Technorati: IValueConverter ,
  45. WP7
  46. , binding , phone windows 7 , background , solidbrush , color, colors

Tuesday, January 4, 2011

Nausea Dizziness Sore Throat

VB for Dummies: The Serialization - Part 1

This post is dedicated to the serialization and how to exploit it in Visual Basic. We start with a definition of serialization socket

Wikipedia

:
In computing, serialization is a process to save an object in a linear storage medium (eg, file or memory area), or for transmission over a network connection. Serialization can be in binary form or may use markup (eg XML) directly readable by humans. The purpose of serialization is to transmit the entire state of the object so that it can later be recreated in exactly the same status from the reverse process is called deserialization. Le classi in gioco sono, evidentemente molto semplici e servono esclusivamente da esempio senza avere la pretesa di essere esaustive.
In dettagli le classi sono le seguenti:

Imports

System.Xml.Serialization

 

Public Class Invoice

image

Public Sub New


() & #

160; Details =
New
  1. List (Of
  2. DettaglioFattura
  3. )
  4. & # 160; End Sub
  5. Public Property DataEmissione As DateTime
  6. Public Property Customer As
  7. Customer
  8. ; Public Property
  9. NumeroDocumento
  10. As String Public Property Details
  11. As
  12. List (Of DettaglioFattura )
  13. Public
  14. Property Stato If StatoFattura
  15. Public ReadOnly Property Total If Decimal
  16. Get
  17. & # 160; If Dettagli Is Nothing
  18. Then
  19.                  Return 0              Else                  Return Dettagli.Sum(
  20. Function
  21. (d) d .TotaleIvato)
  22.              End If          End
  23. Get
  24.     
  25. End
  26. Property
  27.   End Class
  28. Public
  29. Class DettaglioFattura
  30. Public Property
  31. Description As String

Public Property Code
    As String
  1. Public
  2. Property
  3. Quantita
  4. As
  5. Integer      Public Property PrezzoUnitario
  6. As
  7. Decimal      Public Property Iva
  8. As
  9. Decimal        Public
  10. ReadOnly
  11. Property Totale As Decimal         
  12. Get
  13.              Return Quantita * PrezzoUnitario          End
  14. Get
  15.      End Property        Public
  16. ReadOnly Property
  17. TotaleIvato
  18. If
  19. Decimal
  20. Get
  21. Total Return * (1 + Iva) End
  22. Get
  23.      End Property End Class
  24.  
  25. Public
  26. Class
  27. Cliente  
  28.      Public Property Denominazione
  29. As
String

    

Public
Property
CodiceFiscale
    As
  1. String      Public
  2. Property
  3. PartitaIVA
  4. As
  5. String   End
  6. Class
  7.  
  8. Public Enum StatoFattura
  9.     DaPagare
  10.     Pagata     Annullata
  11. End Enum

  1. XML Serialization in The first type of XML serialization is that we will see, that we will see how to "write" the instances of our class invoice formats XML. order to serialize our class in an XML format, the same class must be serializable, which is composed of properties (the methods are not serialized) serializable. If, for example, our class has a property of a type. NET does not serialize the entire class is not serializable. The serialization process is based on the use della classe XmlSerializer e di un oggetto che serva da flusso in cui scrivere l’XML risultante (un XmlWriter, un TextWriter, uno Stream).
  2. In particolare il costruttore dell’XmlSerializer prevede che venga dichiarata per quale classe stiamo costruendo il serializzatore, quindi possiamo utilizzare il metodo Serialize() per scrivere l’XML risultatnte nello stream o nel writer opportuno. La seguente funzione restituisce la stringa XML utilizzando uno StringWriter:
  3. Public Shared
  4. Function
SerializzaXML(
ByVal
fattura
As

Fattura

)

As

String

    

If

fattura

Is
Nothing
    Then
  1. Throw New ArgumentNullException ( "Fattura" )      Dim strXml As String =
  2. Nothing
  3.      Dim writer As New XmlSerializer ( GetType ( Fattura ))     
  4. Using
  5. strWriter As New StringWriter ()         
  6. writer
  7. .Serialize(strWriter, fattura)         strXml = strWriter .ToString()      End Using     
  8. Return
  9. strXml End Function
  10. La seguente figura mostra la serializzazione di una fattura di prova:
  11. Come possiamo osservare, tutte le proprietà della nostra classe vengono riportate all’interno dell’XML frutto della serializzazione. Ogni proprietà diventa un tag XML con il nome pari al nome della proprietà. Infine lo stato della fattura (definito come un’enumerazione) viene scritto come una stringa esattamente pari al valore dell’enumerazione impostato. A livello di codice, nel momento in cui viene eseguito il Serialize, vengono richiamati tutti Get the properties of read / write class (if not above the total property). In fact, the behavior seen earlier, is the default, but we can intervene to change the result of the XML and we can do it using the appropriate attributes in the namespace System.Xml.Serialization copntenuti.
  12. If we, for example, that one or more properties of our class do not fall within the XML, we can use the attribute XmlIgnoreAttribute decorating their property (ol'attributo) that do not want to end up in XML .
  13. For example, suppose you have una proprietà della nostra fattura, chiamata Id, che non vogliamo serializzare. Potremo scrivere:
  14. < XmlIgnore
  15. ()>
Public

Property

Id

As image Integer ?

In questo modo l’XML che si ottiene non ha il tag <Id>.

In maniera analoga, se vogliamo che una nostra proprietà non diventi un tag XML ma un attributo del tag Fattura, possiamo utilizzare l’attributo XmlAttribute indicando, eventualmente, il nome dell’attributo (altrimenti viene utilizzato il nome della properties):

  1. \u0026lt; XmlAttribute ()>
  2. Public Property NumeroDocumento As String

And if we wanted an XML tag has the name property but a different name, then we could use the XmlElement attribute indicamndo the tag name:

\u0026lt;
  1. XmlElement ( "Issue" )>
  2. Public Property DataEmissione As DateTime

attributes contained in the namespace System.Serialization allow us, therefore, to change the result of serialization from the default.

This is very useful, not so much when we are managing the game and define the schema of XML, but when we are given a standardized template and want to create a mapping of us comfortable with a class we created.
Let's see, now, deserialization, or the reverse process of serialization, ie the procedure that allows us to create an object from XML.
  1. The XmlSerializer allows us to deserialize a string XML into an object. In this case, instead of a writer such as support, we must use a reader:
  2. Public Shared Function DeserializzaXML (ByVal strFattura
  3. As
String) As

Invoice

Dim

retObj

As
Invoice
= Nothing
  1. Dim reader = New XmlSerializer (GetType ( Fattura ))      Dim strReader =
  2. New
  3. StringReader (strFattura)      Try         retObj =
  4. CType
  5. ( reader .Deserialize(strReader), Fattura )      Catch ex As
  6. Exception
  7.          Throw
  8. End Try Return
  9. retObj
  10. End Function
  11. Obviously, if the XML is not adhering to the scheme, we get an exception when deserialized.
  12. But what happens when the deserialization is done? When Deserialize method is called, the class object is instantiated Fattiura (constructor is called) and, therefore, are invoked in sequence sets of properties found in the XML.
  13. For this reason, if we do not place a tag inside the XML file serialized, the resulting property will contain the default value. Attention, therefore, that the properties have a default value consistently. In the next post we will briefly SOAP serialization and, above all, the JSON serialization. Stay Tuned!!
  14. Technorati tags:
serialization,
serialization, XmlSerializer

,

xml

Saturday, January 1, 2011

Gracenotes Cd Database

I am MVP!!

Non sono improvvisamente diventato un pattern architetturale ma sono stato insignito dell’MVP Award per Visual Basic per l’anno 2011!!!

Ho letto e riletto la mail di comunicazione inviatami da Microsoft almeno 10 volte e altrettante volte la rileggerò nel pomeriggio perchè ancora non ci posso credere!!!!

Non so se me lo merito veramente e se ne sono all’altezza, ma la cosa mi gasa all’inverosimile e cercherò di moltiplicare l’impegno per esserne degno!!!!

mia moglie, santa donna, sometimes I neglected to write articles or pills or organize community events. You know that this is my passion and I could not do it;

that allowed me to do community and the way I and I have given me the opportunity to note, the deceased

and his staff that, despite the attempt went wrong, gave me the opportunity to meet people and, in some way, show me.

Technorati tags:

MVP, Visual Basic

    MVP, MVP 2011