Extending the CSLA BusinessBase for some more features?

Extending the CSLA BusinessBase for some more features?

Old forum URL: forums.lhotka.net/forums/t/7000.aspx


AKaplan posted on Monday, May 25, 2009

I would like to extend csla businessbase to feature some options. I was wondering where I should place these features below.

Imports System.Collections.Specialized
Imports System.Xml
Imports System.Text
Imports System.Globalization
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Xml.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.Soap

Public Class Serializer

Public Shared ReadOnly CanBinarySerialize As Boolean

Public Shared Function ConvertToNameValueCollection(ByVal keys As String, ByVal values As String) As NameValueCollection
Dim values2 As New NameValueCollection
If (((keys IsNot Nothing) AndAlso (values IsNot Nothing)) AndAlso ((keys.Length > 0) AndAlso (values.Length > 0))) Then
Dim separator As Char() = New Char() {":"c}
Dim strArray As String() = keys.Split(separator)
For i As Integer = 0 To (strArray.Length / 4) - 1
Dim startIndex As Integer = Integer.Parse(strArray(((i * 4) + 2)), CultureInfo.InvariantCulture)
Dim length As Integer = Integer.Parse(strArray(((i * 4) + 3)), CultureInfo.InvariantCulture)
Dim str As String = strArray((i * 4))
If (((strArray(((i * 4) + 1)) = "S") AndAlso (startIndex >= 0)) AndAlso (values.Length >= (startIndex + length))) Then
values2.Item(str) = values.Substring(startIndex, length)
End If
Next i
End If
Return values2
End Function

Public Shared Sub ConvertFromNameValueCollection(ByVal nvc As NameValueCollection, ByRef keys As String, ByVal values As String, Optional ByVal allowEmptyStrings As Boolean = False)
If ((nvc IsNot Nothing) AndAlso (nvc.Count <> 0)) Then
Dim builder As New StringBuilder
Dim builder2 As New StringBuilder
Dim num As Integer = 0
For Each str As String In nvc.AllKeys
If (str.IndexOf(":"c) <> -1) Then
Throw New ArgumentException("ExtendedAttributes Key can not contain the character "":""")
End If
Dim text As String = nvc.Item(str)
If ((allowEmptyStrings AndAlso ([text] IsNot Nothing)) OrElse Not TypeHelper.IsNullorEmpty([text])) Then
builder.AppendFormat("{0}:S:{1}:{2}:", str, num, [text].Length)
builder2.Append([text])
num = (num + [text].Length)
End If
Next
keys = builder.ToString
values = builder2.ToString
End If
End Sub

Public Shared Sub ConvertFromNameValueBinaryCollection(ByVal nvc As NameValueCollection, ByVal keys As String, ByVal values As String, ByVal binary As Byte(), Optional ByVal allowEmptyStrings As Boolean = False)
If ((nvc IsNot Nothing) AndAlso (nvc.Count <> 0)) Then
Dim builder As New StringBuilder
Dim builder2 As New StringBuilder
Dim builder3 As New StringBuilder
Dim num As Integer = 0
For Each str As String In nvc.AllKeys
If (str.IndexOf(":"c) <> -1) Then
Throw New ArgumentException("ExtendedAttributes Key can not contain the character "":""")
End If
Dim text As String = nvc.Item(str)
If ((allowEmptyStrings AndAlso ([text] IsNot Nothing)) OrElse Not TypeHelper.IsNullorEmpty([text])) Then
builder.AppendFormat("{0}:S:{1}:{2}:{3}", str, num, text.Length, text.Length)
builder2.Append(text)
builder3.Append(text)
num = (num + [text].Length)
End If
Next
keys = builder.ToString
values = builder2.ToString
binary = ConvertObjectToBytes(builder3.ToString)
End If
End Sub

Public Shared Function ConvertSoapToObject(ByVal xml As String, ByVal objectType As Type) As Object
Dim serializationStream As MemoryStream = Nothing
Dim obj2 As Object = Nothing
Try
Dim formatter As IFormatter = New SoapFormatter
serializationStream = New MemoryStream(Encoding.Default.GetBytes(xml))
obj2 = formatter.Deserialize(serializationStream)
Finally
If (serializationStream IsNot Nothing) Then
serializationStream.Close()
End If
End Try
Return obj2
End Function

Public Shared Function ConvertFileToObject(ByVal path As String, ByVal objecttype As Type) As Object
Dim obj2 As Object = Nothing
If ((path IsNot Nothing) AndAlso (path.Length > 0)) Then
Using stream As New FileStream(path, FileMode.Open, FileAccess.Read)
obj2 = New XmlSerializer(objecttype).Deserialize(stream)
stream.Close()
End Using
End If
Return obj2
End Function

Public Shared Function ConvertObjectToBytes(ByVal objectToConvert As Object) As Byte()
Dim buffer As Byte() = Nothing
If Serializer.CanBinarySerialize Then
Dim formatter As New BinaryFormatter
Using stream As New MemoryStream
formatter.Serialize(stream, objectToConvert)
stream.Position = 0
buffer = New Byte(stream.Length - 1) {}
stream.Read(buffer, 0, buffer.Length)
stream.Close()
End Using
End If
Return buffer
End Function

Public Shared Function ConvertByteToObject(ByVal byteArray As Byte()) As Object
Dim obj2 As Object = Nothing
If ((Serializer.CanBinarySerialize AndAlso (byteArray IsNot Nothing)) AndAlso (byteArray.Length > 0)) Then
Dim formatter As New BinaryFormatter
Using stream As New MemoryStream
stream.Write(byteArray, 0, byteArray.Length)
stream.Position = 0
If (byteArray.Length > 4) Then
obj2 = formatter.Deserialize(stream)
End If
stream.Close()
End Using
End If
Return obj2
End Function

Public Shared Function ConvertXmlToObject(ByVal xml As String, ByVal ObjectType As Type) As Object
Dim obj2 As Object = Nothing
If Not TypeHelper.IsNullorEmpty(xml) Then
Using reader As New StringReader(xml)
obj2 = New XmlSerializer(ObjectType).Deserialize(reader)
reader.Close()
End Using
End If
Return obj2
End Function

Public Shared Function ConvertXmlNodeToObject(ByVal node As XmlNode, ByVal ObjectType As Type) As Object
Dim obj2 As Object = Nothing
If (node IsNot Nothing) Then
Using reader As New StringReader(node.OuterXml)
obj2 = New XmlSerializer(ObjectType).Deserialize(reader)
reader.Close()
End Using
End If
Return obj2
End Function

Public Shared Function ConvertObjectToSoapString(ByVal obj As Object) As String
Dim serializationStream As New MemoryStream
Dim formatter As IFormatter = New SoapFormatter
Dim str As String = String.Empty
Try
formatter.Serialize(serializationStream, obj)
Dim length As Integer = CInt(serializationStream.Length)
Dim buffer As Byte() = New Byte(length - 1) {}
serializationStream.Seek(0, SeekOrigin.Begin)
serializationStream.Read(buffer, 0, length)
Dim encoding As New UTF8Encoding
str = encoding.GetString(buffer).Trim
Finally
If (serializationStream IsNot Nothing) Then
serializationStream.Close()
End If
End Try
Return str
End Function

Public Shared Function ConvertByteToString(ByVal arr As Byte()) As String
Return Convert.ToBase64String(arr)
End Function
Public Shared Function ConvertXmlToString(ByVal objectToConvert As Object) As Object
Dim str As String = Nothing
If (objectToConvert IsNot Nothing) Then
Dim serializer As New XmlSerializer(objectToConvert.GetType)
Using writer As New StringWriter(CultureInfo.InvariantCulture)
serializer.Serialize(DirectCast(writer, TextWriter), objectToConvert)
str = writer.ToString
writer.Close()
End Using
End If
Return str
End Function

Public Shared Function LoadBinaryFile(ByVal path As String) As Object
If Not File.Exists(path) Then
Return Nothing
End If
Using stream As New FileStream(path, FileMode.Open, FileAccess.Read)
Dim reader As New BinaryReader(stream)
Dim buffer As Byte() = New Byte(stream.Length - 1) {}
reader.Read(buffer, 0, CInt(stream.Length))
Return Serializer.ConvertByteToObject(buffer)
End Using
End Function

Public Shared Function SaveAsBinary(ByVal objectToSave As Object, ByVal path As String) As Boolean
If ((objectToSave IsNot Nothing) AndAlso Serializer.CanBinarySerialize) Then
Dim buffer As Byte() = Serializer.ConvertObjectToBytes(objectToSave)
If (buffer IsNot Nothing) Then
Using stream As New FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)
Using writer As New BinaryWriter(stream)
writer.Write(buffer)
Return True
End Using
End Using
End If
End If
Return False
End Function

Public Shared Sub SaveAsXML(ByVal objectToConvert As Object, ByVal path As String)
If (objectToConvert IsNot Nothing) Then
Dim serializer As New XmlSerializer(objectToConvert.GetType)
Using writer As New StreamWriter(path)
serializer.Serialize(DirectCast(writer, TextWriter), objectToConvert)
writer.Close()
End Using
End If
End Sub

Public Shared Function XMLDecode(ByVal sTmp As String) As String
Dim numArray As Integer() = New Integer() {38, 60, 62, 34, 61, 39}
For i As Integer = 0 To numArray.Length - 1
sTmp = sTmp.Replace(("&#" & numArray(i).ToString & ";"), DirectCast(ChrW(numArray(i)), Char).ToString)
Next i
Return sTmp
End Function

Public Shared Function XMLEncode(ByVal sTmp As String) As String
Dim numArray As Integer() = New Integer() {38, 60, 62, 34, 61, 39}
For i As Integer = 0 To numArray.Length - 1
sTmp = sTmp.Replace(DirectCast(ChrW(numArray(i)), Char).ToString, ("&#" & numArray(i).ToString & ";"))
Next i
Return sTmp
End Function

End Class

_
Public Class ExtendedAttributes

Private _extendedAttribute As NameValueCollection

Public ReadOnly Property ExtendedAttributeCount() As Integer
Get
Return _extendedAttribute.Count
End Get
End Property

Public Function GetExtendedAttribute(ByVal name As String) As String
Dim str As String = _extendedAttribute.Item(name)
If str Is Nothing Then
Return String.Empty
End If
Return str
End Function

Public Sub SetExtendedAttribute(ByVal name As String, ByVal value As String)
If (name.IndexOf("PollItem") > -1) Then
Debug.WriteLine(String.Concat(New String() {"Setting '", name, "' to '", value, "'"}))
End If
If ((value Is Nothing) OrElse (value = String.Empty)) Then
_extendedAttribute.Remove(name)
Else
_extendedAttribute.Item(name) = value
End If
End Sub

Public Function GetSerializerData() As SerializerData
Dim _data As New SerializerData
Dim _keys As String = String.Empty
Dim _values As String = String.Empty
Serializer.ConvertFromNameValueCollection(_extendedAttribute, _keys, _values)
_data.Keys = _keys
_data.Values = _values
Return _data
End Function

Public Sub SetSerializerDate(ByVal data As SerializerData)
If ((_extendedAttribute Is Nothing) OrElse (_extendedAttribute.Count = 0)) Then
_extendedAttribute = Serializer.ConvertToNameValueCollection(data.Keys, data.Values)
End If
If (_extendedAttribute Is Nothing) Then
_extendedAttribute = New NameValueCollection
End If
End Sub

End Class

JoeFallon1 replied on Tuesday, May 26, 2009

One of the key recommendations has always been to create your own Generic Base class for each CSLA stereotype. Each of your classes inherits from its corresponding CSLA class. e.g. MyBusinessBase(Of T) inherits from BusinessBase(Of T).

Then all of your BOs should inherit from your base classes. Then when you want to extend CSLA in some way you only need to add code to MyBusinessBase and all of your root BOs will now have the new behavior.

Joe

AKaplan replied on Tuesday, May 26, 2009

oh yea... duhh...

Copyright (c) Marimer LLC