'Programming'에 해당되는 글 64건

  1. [vb.net] ISerializable 를 상속 받아 serializable class 구현하기 2
  2. 한국 eXtreme Programming 사용자 모임
  3. 웹 플랫폼
  4. 데이터베이스에서 스토어드 프로시져를 이용하여 테이블을 읽어서 XML파일을 압축하는 코드입니다.
  5. [WPF] XAML (Extensible Application Markup Language)
  6. [WPF] WPF란?
  7. [VB.NET] 로컬PC의 IP Address 가져오기
  8. [VB.NET] MAC Address 가지오기
  9. WCF 를 사용한 주식거래 시스템 예제
  10. 간단한 WCF서비스의 클라이언트 생성

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

http://xper.org/wiki/xp/_b4_eb_b9_ae


한국 eXtreme Programming 사용자 모임

웹 플랫폼

웹 플랫폼 인스톨러 http://www.microsoft.com/web/downloads/platform.aspx

웹 플랫폼 인스톨러는 윈도우 서버에서 사용되는 모든 웹 플랫폼 프레임워크, 웹 어플리케이션, IIS 확장 기능 및 SQL서버와 같은 제품 등에 대한 설치와 구성을 돕는 최고의 툴입니다.

데이터베이스에서 스토어드 프로시져를 이용하여 테이블을 읽어서 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


[WPF] XAML(Extensible Application Markup Language)

XAML이 WPF의 컨트롤과 컨트롤의 레이아웃을 정의한다
디자이너이면 Microsoft Expression Blend을 이용하게 될 것이고, 개발자면 비주얼 스튜디오를 사용한다

비주얼 스튜디오에서 XAML 컴파일을 하게 되면 BAML(바이너리)로 변환되게 된다.

** top-level element
• Window
• Page (which is similar to Window, but used for navigable applications)
• Application (which defines application resources and startup settings)


** The Code-Behind Class
<Window x:Class="WindowsApplication1.Window1"

namespace WindowsApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }
}
}

** Attached Properties- DefiningType.PropertyName
They’re actually translated into method
calls.

example)
<TextBox ... Grid.Row="0">
[Place question here.]
</TextBox>

--> Grid.SetRow(txtQuestion, 0);

** Special Characters andWhitespace
<Button ... >
<Click Me>
</Button>
--> should be
<Button ... >
&lt;Click Me&gt;
</Button>

<TextBox Name="txtQuestion" xml:space="preserve" ...>
[There is a lot of space inside these quotation marks " ".]
</TextBox>


** Events
<Button ... Click="cmdAnswer_Click">


** Using Types from Other Namespaces
xmlns:Prefix="clr-namespace:Namespace;assembly=AssemblyName"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:MyNamespace"

<local:MyObject ...></local:MyObject>

XAML doesn’t support parameterized constructors, and all the elements
in WPF elements include a no-argument constructor.

<Window x:Class="WindowsApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Width="300" Height="300"
>
<ListBox>
<ListBoxItem>
<sys:DateTime>10/13/2010 4:30 PM</sys:DateTime>
</ListBoxItem>
<ListBoxItem>
<sys:DateTime>10/29/2010 12:30 PM</sys:DateTime>
</ListBoxItem>
<ListBoxItem>
<sys:DateTime>10/30/2010 2:30 PM</sys:DateTime>
</ListBoxItem>
</ListBox>
</Window>

** Loading and Compiling XAML

[WPF] WPF란?

WPF는 Direct X를 사용한다. 기존의 GDI/GDI+를 사용하지 않는다.

** 하드웨어 가속과 WPF
WPF는 소프트웨어 계산을 사용하는 모든 것을 수행할 수 있는 능력을 가지고 있다. 즉, 비디오 카드에 내장된 특정 지원에 의존적이지 않다

WPF는 Vista에서 더욱 좋은 성능을 발휘한다. 이유는 WDDM(Windows Vista Display Driver Model (WDDM))
또한, 오래된 비디오카드가 장착된 컴퓨터로는 WPF 어플리케이션을 잘 구동시킬 수 없다. 물론 기존의 GDI 타입보다는 빠른 성능을 보여주긴 한다.

** WPF: A Higher-Level API
A web-like layout model - 컨트롤 사이즈를 자유롭게 운용
A rich drawing model
A rich text model
Animation as a first-class programming concept.
Support for audio and video media.
Support for audio and video media.
Commands
Declarative user interface.
Page-based applications

** Resolution Independence

** New Features in WPF 3.5
Firefox support for XBAPs
Data binding support for LINQ.
Data binding support for IDataErrorInfo
Support for placing interactive controls (such as buttons) inside a RichTextBox control.
Support for placing 2-D elements on 3-D surfaces.
An add-in model.

** Windows Forms Lives On
윈도우즈 폼 컨트롤도 WPF안에서 사용되지 질 수 있다. 윈도우 폼을 수용함으로 새로운 윈도우 기반 프로젝트에서는 적용할만 하다.

** Silverlight
FireFox와 Internet Exlore를 지원하는 WPF, 웹기반 어플리케이션일지라도 결국은 윈도우 OS기반에서만 돌아간다. 그러나 실버라이트는 리눅스상의 웹브라우져에서도 구동한다.


** Class Hierachy

사용자 삽입 이미지

WPF 네임스페이스는 System.Windows, System.WIndows.Controls, System.Windows.Media 와 같은 구조를 가진다.


- System.Threading.DispatcherObject
- System.Windows.DependencyObject
- System.Windows.Media.Visual
- System.Windows.UIElement
- System.Windows.FrameworkElement
- System.Windows.Shapes.Shape
- System.Windows.Controls.Control
- System.Windows.Controls.ContentControl
- System.Windows.Controls.ItemsControl
- System.Windows.Controls.Panel

[VB.NET] 로컬PC의 IP Address 가져오기

    ''' <summary>
    ''' Show IP address of my local pc
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ShowMyIP()
        Dim IPHEntry As IPHostEntry
        IPHEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName())
        lblMyIP.Text = IPHEntry.AddressList(0).ToString()

    End Sub

MAC Address 가져오기


    Private Function GetMacAddress()
        Dim mc As System.Management.ManagementClass
        Dim mo As System.Management.ManagementObject
        mc = New System.Management.ManagementClass("Win32_NetworkAdapterConfiguration")
        Dim moc As System.Management.ManagementObjectCollection = mc.GetInstances()
        For Each mo In moc
            If mo.Item("IPEnabled") = True Then
                Return mo.Item("MacAddress").ToString()
            End If
        Next
        Return String.Empty
    End Function

WCF 를 사용한 주식거래 시스템 예제

http://msdn.microsoft.com/en-us/netframework/bb499684.aspx

사용자 삽입 이미지

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()