'VB.NET'에 해당되는 글 4건

  1. [vb.net] class에 대한 clone의 구현
  2. [vb.net] ISerializable 를 상속 받아 serializable class 구현하기 2
  3. 데이터베이스에서 스토어드 프로시져를 이용하여 테이블을 읽어서 XML파일을 압축하는 코드입니다.
  4. 간단한 WCF서비스의 클라이언트 생성

[vb.net] class에 대한 clone의 구현

class는 레퍼런스 타입인데 여기에 ICloneable의 Clone메서드를 구현하여 class의 내부값들을 그대로 복제할 수 있는 기능을 구현한다. 레퍼런스 타입은 하나의 메모리를 가리키고 있으므로 특정 인스턴스 값을 변경하면 다른 인스턴스의 값도 변경된다. 이를 극복하기 위하여 Clone 을 사용한다.

MemberwiseClone 메소드는 모든 value 타입 필드의 값을 그대로 복제하고 참조 타입인 경우는 참조로서 복제한다. 따라서 클래스 내부에 참조 타입 필드는 새로 생성하여 값을 옮겨 넣는 과정이 필요하다(shopping 클래스의 clone메서드와 order클래스의 clone메서드의 차이)

-- order.vb --
Imports System
Imports System.Text
Imports System.Collections.Generic

Public Class Order
    Implements ICloneable

    Public OrderNumber As String
    Public PONumber As String
    Public ShippingAddress As String

    Public Sub New(ByVal _OrderNumber As String, ByVal _PONumber As String, ByVal _ShippingAddress As String)
        OrderNumber = _OrderNumber
        PONumber = _PONumber
        ShippingAddress = _ShippingAddress
    End Sub

    ' create a clone
    Public Function Clone() As Object Implements System.ICloneable.Clone
        Return Me.MemberwiseClone
    End Function

    Public Overrides Function ToString() As String
        Return String.Format("Order Number is {0}, and PO number is {1}", OrderNumber, PONumber)
    End Function
End Class

-- shopping.vb --
Imports System
Imports System.Text
Imports System.Collections.Generic

Public Class Shopping
    Implements ICloneable

    Public Orders As New List(Of Order)

    Public Sub New()

    End Sub

    Public Overrides Function ToString() As String
        Dim str As New StringBuilder
        For Each e As Order In Orders
            str.AppendLine(String.Format("order{0}", e.OrderNumber))
        Next
        Return str.ToString
    End Function

    Public Function Clone() As Object Implements System.ICloneable.Clone
        Dim newShopping As New Shopping

        For Each e As Order In Me.Orders
            newShopping.Orders.Add(DirectCast(e.Clone, Order))
        Next

        Return newShopping
    End Function
End Class


--  module 1 --
Module Module1

    Sub Main()
        Dim originalShopping As New Shopping
        originalShopping.Orders.Add(New Order("0001", "P001", "address1"))
        originalShopping.Orders.Add(New Order("0002", "P002", "address2"))
        originalShopping.Orders.Add(New Order("0003", "P003", "address3"))

        Dim clonedShopping As Shopping = DirectCast(originalShopping.Clone, Shopping)

        originalShopping.Orders(0).OrderNumber = "0005"
        originalShopping.Orders(0).PONumber = "P005"
        originalShopping.Orders(0).ShippingAddress = "address5"

        Console.WriteLine(originalShopping.ToString)
        Console.WriteLine(clonedShopping.ToString)
        Console.ReadLine()
    End Sub

End Module

ISerializable 를 상속 받아 serializable class 구현하기

Imports System
Imports System.IO
Imports System.Text
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary

Module Module1

    Sub Main()
        Dim order As New Order("1002", "My First Order", "Seoul, Korea")
        Console.WriteLine(order.ToString)

        Dim str As Stream = File.Create("MyOrder.bin")
        Dim bf As New BinaryFormatter

        ' serialize the order object specifying another application domatin
        ' as the destination of the serialized data. All data including the employee addrsss is serialized
        bf.Context = New StreamingContext(StreamingContextStates.CrossAppDomain)
        bf.Serialize(str, order)
        str.Close()

        ' deselialize and display the order object
        str = File.OpenRead("MyOrder.bin")
        bf = New BinaryFormatter
        order = DirectCast(bf.Deserialize(str), Order)
        str.Close()
        Console.WriteLine(order.ToString())

        ' selialize the order object specifying a file as the destination
        ' of the selialized data. In this case, the order addrsss is not include in the serialized data

        str = File.Create("MyNextOrder.bin")
        bf = New BinaryFormatter
        bf.Context = New StreamingContext(StreamingContextStates.File)
        bf.Serialize(str, order)

        str.Close()

        str = File.OpenRead("MyNextOrder.bin")
        bf = New BinaryFormatter
        order = DirectCast(bf.Deserialize(str), Order)
        str.Close()
        Console.WriteLine(order.ToString)

        Console.WriteLine("")
        Console.WriteLine("Main method is completed, please Enter")
        Console.ReadLine()
    End Sub

End Module


--- Order.vb ----
Imports System
Imports System.IO
Imports System.Text
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary

<Serializable()> _
Public Class Order
    Implements ISerializable

    Private m_OrderNumber As String
    Private m_PONumber As String
    Private m_ShippingAddress As String

    Public Sub New(ByVal OrderNumber As String, _
                   ByVal PONumber As String, _
                   ByVal ShippingAddress As String)
        m_OrderNumber = OrderNumber
        m_PONumber = PONumber
        m_ShippingAddress = ShippingAddress
    End Sub

    ' when deserialized, it will be executed
    Private Sub New(ByVal Info As SerializationInfo, ByVal context As StreamingContext)
        m_OrderNumber = Info.GetString("OrderNumber")
        m_PONumber = Info.GetString("PONumber")

        Try
            m_ShippingAddress = Info.GetString("ShippingAddress")
        Catch ex As Exception
            m_ShippingAddress = Nothing
        End Try
    End Sub

    Public Property OrderNumber() As String
        Get
            Return m_OrderNumber
        End Get
        Set(ByVal value As String)
            m_OrderNumber = value
        End Set
    End Property

    Public Property PONumber() As String
        Get
            Return m_PONumber
        End Get
        Set(ByVal value As String)
            m_PONumber = value
        End Set
    End Property

    Public Property ShippingAddress() As String
        Get
            If m_ShippingAddress Is Nothing Then
                m_ShippingAddress = String.Empty
            End If
            Return m_ShippingAddress
        End Get
        Set(ByVal value As String)
            m_ShippingAddress = value
        End Set
    End Property

    ''' <summary>
    '''  when serialized, it will be invoked
    ''' </summary>
    ''' <param name="info"></param>
    ''' <param name="context"></param>
    ''' <remarks></remarks>
    Public Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData
        info.AddValue("OrderNumber", OrderNumber)
        info.AddValue("PONumber", PONumber)

        If (context.State And StreamingContextStates.File) = 0 Then
            info.AddValue("ShippingAddress", ShippingAddress)
        End If

    End Sub

    Public Overrides Function ToString() As String
        Dim str As New StringBuilder
        str.AppendLine(String.Format("Order Number: {0}", OrderNumber))
        str.AppendLine(String.Format("PO Number: {0}", PONumber))
        str.AppendLine(String.Format("Shipping Address: {0}", ShippingAddress))
        Return str.ToString
    End Function
End Class

데이터베이스에서 스토어드 프로시져를 이용하여 테이블을 읽어서 XML파일을 압축하는 코드입니다.

ICSharpCode.SharpZipLib.dll을 참조에 추가한다. 자세한 내용은 http://www.sharpdevelop.net/OpenSource/SharpZipLib/Default.aspx을 참조하도록 합니다.

Imports ICSharpCode.SharpZipLib

   ' read path
        Dim savePath As String = String.Empty
        Dim fPath As String = String.Empty
        Dim dataVersion As String = String.Empty
        Dim CRC32 As Checksums.Crc32 = Nothing
        Dim zipOut As Zip.ZipOutputStream = Nothing
        Dim zipEntry As Zip.ZipEntry = Nothing
        Try
            savePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings("sizer.savePath"))
            fPath = System.IO.Path.Combine(savePath, DatafileFileName)
            Try
                Dim ds As New DataSet("PAXDataSet")
                ds.Namespace = "http://tempuri.org/PAXDataSet.xsd"
                Dim adapt As New SqlClient.SqlDataAdapter("스토어드 프로시져", ConfigurationManager.ConnectionStrings("PAXConnectionString").ConnectionString)
                adapt.Fill(ds)

               '  'Table'테이블에서 각 테이블의 이름을 가져와서 이를 맵핑시킨다.
                For Each row As DataRow In ds.Tables("Table").Rows
                    If ds.Tables(row("SourceTable").ToString) IsNot Nothing Then
                        ds.Tables(row("SourceTable").ToString).TableName = row("MappedTable").ToString
                    End If
                Next

                ds.Tables.Remove("Table")
                ds.AcceptChanges()

                If File.Exists(fPath) Then
                    File.SetAttributes(fPath, FileAttributes.Normal)
                End If

                dataVersion = {버전을 넣습니다.}

                Dim data As String = ds.GetXml.Trim
                Dim buffer() As Byte = System.Text.Encoding.UTF8.GetBytes(data)

                zipOut = New SharpZip.Zip.ZipOutputStream(File.Create(fPath))
                zipOut.SetLevel(9)
                zipOut.SetComment(dataVersion)
                zipOut.Password = {패스워드}
                CRC32 = New Checksums.Crc32
                zipEntry = New Zip.ZipEntry({파일명})
                zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated
                zipEntry.Comment = dataVersion
                CRC32.Reset()
                CRC32.Update(buffer)
                zipEntry.Crc = CRC32.Value
                zipEntry.DateTime = DateTime.Now
                zipEntry.Size = buffer.Length
                zipOut.PutNextEntry(zipEntry)
                zipOut.Write(buffer, 0, buffer.Length)
                zipOut.Flush()
            Finally
                If zipOut IsNot Nothing Then
                    Try
                        zipOut.Finish()
                        zipOut.Close()
                        zipOut.Dispose()
                    Catch : End Try
                End If
            End Try
        Catch ex As Exception
            [Throw Exception...]
        End Try


1.  WCF 서비스를 사용할 클라이언트로서 윈도우폼 어블리케이션을 생성한다

사용자 삽입 이미지

2. Project의 Reference에 System.ServiceModel를 추가한다

3. 프로젝트에 Add Service Reference를 선택한다. 그리고 Address에 http://localhost:8000/dosc 를 입력하고 GO버튼을 클릭한다. 이때 WCF서비스는 호스트되고 있어야 한다
사용자 삽입 이미지



4. UI는 다음의 그림과 같이 구성한다
사용자 삽입 이미지


5. button Click 이벤트에 다음의 코드를 추가한다
        Dim result As Integer
        Dim ws As New CalculatorService.CalculatorClient()

        ws.Open()

        If RadioButton1.Checked = True Then
            result = ws.Add(Integer.Parse(TextBox1.Text), Integer.Parse(TextBox2.Text))
        ElseIf RadioButton2.Checked = True Then
            result = ws.Subtract(Integer.Parse(TextBox1.Text), Integer.Parse(TextBox2.Text))
        ElseIf RadioButton3.Checked = True Then
            result = ws.Multiply(Integer.Parse(TextBox1.Text), Integer.Parse(TextBox2.Text))
        ElseIf RadioButton4.Checked = True Then
            result = ws.Divide(Integer.Parse(TextBox1.Text), Integer.Parse(TextBox2.Text))
        End If

        ws.Close()

        Label1.Text = result.ToString()