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

0 comments:

Post a Comment