LazyDreamy

관리자 | 글쓰기

LazyDreamy » Search » Results » Articles

VB.NET와 관련된 글 6개

  1. 2010/03/07 .NET Socket Programming (for data arriving event) (1)
  2. 2009/02/08 [VB.Net] 시스템 내부 고유 값 알아오기. (2)
  3. 2008/12/07 [VB] INI Read / Write (3)
  4. 2008/12/07 [VB] Datagrid to Excel export
  5. 2008/12/06 [VB] DataGridView 에서 Selected rows 가져오기 (1)
  6. 2008/10/25 [VB] 파일 경로 추출

LazyDreamy » Computer/Programming

.NET Socket Programming (for data arriving event)

드림 | 2010/03/07 23:09

Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text

' State object for receiving data from remote device.

Public Class StateObject
    ' Client socket.
    Public workSocket As Socket = Nothing
    ' Size of receive buffer.
    Public Const BufferSize As Integer = 256
    ' Receive buffer.
    Public buffer(BufferSize) As Byte
    ' Received data string.
    Public sb As New StringBuilder
End Class 'StateObject

Public Class AsynchronousClient
    ' The port number for the remote device.
    Private Const port As Integer = 11000

    ' ManualResetEvent instances signal completion.
    Private Shared connectDone As New ManualResetEvent(False)
    Private Shared sendDone As New ManualResetEvent(False)
    Private Shared receiveDone As New ManualResetEvent(False)

    ' The response from the remote device.
    Private Shared response As String = String.Empty

    Public Shared Sub Main()
        ' Establish the remote endpoint for the socket.
        ' For this example use local machine.
        Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
        Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
        Dim remoteEP As New IPEndPoint(ipAddress, port)

        ' Create a TCP/IP socket.
        Dim client As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

        ' Connect to the remote endpoint.
        client.BeginConnect(remoteEP, New AsyncCallback(AddressOf ConnectCallback), client)

        ' Wait for connect.
        connectDone.WaitOne()

        ' Send test data to the remote device.
        Send(client, "This is a test<EOF>")
        sendDone.WaitOne()

        ' Receive the response from the remote device.
        Receive(client)
        receiveDone.WaitOne()

        ' Write the response to the console.
        Console.WriteLine("Response received : {0}", response)

        ' Release the socket.
        client.Shutdown(SocketShutdown.Both)
        client.Close()
    End Sub 'Main

    Private Shared Sub ConnectCallback(ByVal ar As IAsyncResult)
        ' Retrieve the socket from the state object.
        Dim client As Socket = CType(ar.AsyncState, Socket)

        ' Complete the connection.
        client.EndConnect(ar)

        Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString())

        ' Signal that the connection has been made.
        connectDone.Set()
    End Sub 'ConnectCallback

    Private Shared Sub Receive(ByVal client As Socket)

        ' Create the state object.
        Dim state As New StateObject
        state.workSocket = client

        ' Begin receiving the data from the remote device.
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
    End Sub 'Receive

    Private Shared Sub ReceiveCallback(ByVal ar As IAsyncResult)

        ' Retrieve the state object and the client socket
        ' from the asynchronous state object.
        Dim state As StateObject = CType(ar.AsyncState, StateObject)
        Dim client As Socket = state.workSocket

        ' Read data from the remote device.
        Dim bytesRead As Integer = client.EndReceive(ar)

        If bytesRead > 0 Then
            ' There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))

            ' Get the rest of the data.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state)
        Else
            ' All the data has arrived; put it in response.
            If state.sb.Length > 1 Then
                response = state.sb.ToString()
            End If
            ' Signal that all bytes have been received.
            receiveDone.Set()
        End If
    End Sub 'ReceiveCallback

    Private Shared Sub Send(ByVal client As Socket, ByVal data As String)
        ' Convert the string data to byte data using ASCII encoding.
        Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)

        ' Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), client)
    End Sub 'Send

    Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
        ' Retrieve the socket from the state object.
        Dim client As Socket = CType(ar.AsyncState, Socket)

        ' Complete sending the data to the remote device.
        Dim bytesSent As Integer = client.EndSend(ar)
        Console.WriteLine("Sent {0} bytes to server.", bytesSent)

        ' Signal that all bytes have been sent.
        sendDone.Set()
    End Sub 'SendCallback
End Class 'AsynchronousClient


출처 : http://msdn.microsoft.com/en-us/library/bew39x2a.aspx


winsock 을 강제로 사용하지 않고, .net 내장 함수를 사용하려고 찾다 보니 소켓 이벤트 형태를 지원한다.

2010/03/07 23:09 2010/03/07 23:09


태그

(go to top)

LazyDreamy » Computer/Programming

[VB.Net] 시스템 내부 고유 값 알아오기.

드림 | 2009/02/08 09:23

일단 기본적으로 사용되는 시스템에 고유 값을 가진 장치들에서 해당 값을 가져와야 한다. 문제는 이 사이에 권한이나 다른 부분이 엮여있을 수 있다는 것. (가장 간단한 건 기 작성된 라이브러리 활용인 듯 하다-_-;)

일단 여기서는 추가 비용없이..; WMI 를 사용한 코드를 사용하였다. (XP이상에서 동작한다)


일단 WMI 삽질을 위해 Import

Imports System.Management


특정 드라이브의 볼륨 시리얼 넘버 가져오기

Public Function GetVolumeSerialNumber(ByVal driveletter As String) As String
    Dim mobjSearcher As New ManagementObjectSearcher("SELECT VolumeSerialNumber FROM Win32_LogicalDisk WHERE Name = '" & driveletter & ":'")
    For Each obj As ManagementObject In mobjSearcher.Get
        Return obj("VolumeSerialNumber")
    Next
    Return -1
End Function

GetVolumeSerialNumber("C")


SerialNumber 를 가져오면 장치 자체의 생산 시리얼을 가져 올 수 있는데, 이 부분에서 접근 문제가 자꾸 발생해서 볼륨시리얼로 대체했다. 단 이 볼륨 시리얼은 위/변조가 가능하며, 파티셔닝 등에 따라 교체된다. 뭐 보통 인증 등에 사용하니까 좀 까탈스러워도 되겠지;


ProcessID (CPU 고유값) 가져오기

Private Function GetProcessor() As String
    Dim mobjSearcher As New ManagementObjectSearcher("SELECT Processorid FROM Win32_Processor")
    For Each obj As ManagementObject In mobjSearcher.Get
        Return obj("Processorid")
    Next
    Return -1
End Function


인터넷 연결 여부 확인 / 해당 NIC 의 MAC Address 와 IP Address 가져오기


Public nicMacAddress As String
Public nicIpAddress As String
Public nicDesc As String

Public Function IsNetworkConnected() As Boolean
    Dim connected As Boolean = SystemInformation.Network
    If connected Then
        connected = False
        'Dim query As String = "SELECT NetConnectionStatus FROM Win32_NetworkAdapter"
        Dim mobjSearcher As New ManagementObjectSearcher("SELECT NetConnectionStatus, MacAddress FROM Win32_NetworkAdapter")
        For Each obj As ManagementObject In mobjSearcher.Get
            If Not IsDBNull(obj("NetConnectionStatus")) Then
                If Convert.ToInt32(obj("NetConnectionStatus")).Equals(2) Then
                    nicMacAddress = obj("Macaddress")
                    connected = True
                    Return connected
                End If
            End If
        Next
        Return connected
    End If
End Function

Public Sub getNetworkInfoFromMACAddress(ByVal MacAddress As String)
    Dim mobjSearcher As New ManagementObjectSearcher("SELECT * From Win32_NetworkAdapterConfiguration WHERE IPEnabled = 1 AND MacAddress = '" & MacAddress & "'")
    For Each obj As ManagementObject In mobjSearcher.Get
        Try
            nicIpAddress = obj("Ipaddress")(0)
            Try
                nicDesc = obj("Description")
            Catch ex As Exception

            End Try
        Catch ex As Exception

        End Try
    Next
End Sub


코드는 여기저기서 참고하고 짜집은 상태라 너덜너덜하며 –_-;;
특히 NIC 관련해서는 2개 이상 연결도 고려해야 하지만.. 과감히 패스!;

연결에서 찾아진 MAC Address 로 IP Address 와 DESC 정보 알아오는 부분 추가

2009/02/08 09:23 2009/02/08 09:23


태그 ,

(go to top)

LazyDreamy » Computer/Programming

[VB] INI Read / Write

드림 | 2008/12/07 11:13

Public INIFILE As String

'INI 스트링을 읽어오기 위한 API 선언
Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" _
    (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpDefault As String, _
    ByVal lpReturnedString As String, ByVal nSize As Int32, ByVal lpFileName As String) As Long

'INI 스트링을 기록하기 위한 API 선언
Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" _
    (ByVal lpApplicationName As String, ByVal lpKeyName As String, ByVal lpString As String, _
    ByVal lpFileName As String) As Long

Public Function INIRead(ByVal Session As String, ByVal KeyValue As String, ByVal INIFILE As String) As String
    'INI 값 읽기
    Dim str As String
    Dim ReturnValue As Long
    str = Space(255)

    ReturnValue = GetPrivateProfileString(Session, KeyValue, "", str, 255, INIFILE)
    str = str.Substring(0, Len(str) - 1)
    str = Trim(str)
    INIRead = str
End Function

Public Function INIWrite(ByVal Session As String, ByVal KeyValue As String, ByVal DataValue As String, ByVal INIFILE As String) As String
    'INI 값 기록
    Dim ReturnValue As Long

    ReturnValue = WritePrivateProfileString(Session, KeyValue, DataValue, INIFILE)
End Function

Public Sub SetInifile()
    Dim path As String = getMyPath()
    Dim filename As String = getMyFilename()

    'Setup.ini 세팅
    INIFILE = path & "\" & filename & ".ini"
End Sub

Public Function getMyPath() As String
    Return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location)
End Function

Public Function getMyFilename() As String
    Return System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly.Location)
End Function


사용


INIWrite("session", "key", "value", INIFILE)
INIRead("session", "key", INIFILE))


설정파일엔 ini 가 제 맛..;;
프로그램이 갈수록.. 파서 덩어리가 되가네 –_-;;;

2008/12/07 11:13 2008/12/07 11:13


태그 , ,

(go to top)

LazyDreamy » Computer/Programming

[VB] Datagrid to Excel export

드림 | 2008/12/07 05:16

Private Declare Function ShellEx Lib "shell32.dll" Alias "ShellExecuteA" ( _
    ByVal hWnd As Integer, ByVal lpOperation As String, _
    ByVal lpFile As String, ByVal lpParameters As String, _
    ByVal lpDirectory As String, ByVal nShowCmd As Integer) As Integer


Private Sub exportExcel(ByVal grdView As DataGridView, ByVal fileName As String, _
ByVal fileExtension As String, ByVal filePath As String)

    ' Choose the path, name, and extension for the Excel file
    Dim myFile As String = filePath & "\" & fileName & fileExtension

    ' Open the file and write the headers
    Dim fs As New IO.StreamWriter(myFile, False)
    fs.WriteLine("<?xml version=""1.0""?>")
    fs.WriteLine("<?mso-application progid=""Excel.Sheet""?>")
    fs.WriteLine("<ss:Workbook xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet"">")

    ' Create the styles for the worksheet
    fs.WriteLine("  <ss:Styles>")
    ' Style for the column headers
    fs.WriteLine("    <ss:Style ss:ID=""1"">")
    fs.WriteLine("      <ss:Font ss:Bold=""1""/>")
    fs.WriteLine("      <ss:Alignment ss:Horizontal=""Center"" ss:Vertical=""Center"" " & _
        "ss:WrapText=""1""/>")
    fs.WriteLine("      <ss:Interior ss:Color=""#C0C0C0"" ss:Pattern=""Solid""/>")
    fs.WriteLine("    </ss:Style>")
    ' Style for the column information
    fs.WriteLine("    <ss:Style ss:ID=""2"">")
    fs.WriteLine("      <ss:Alignment ss:Vertical=""Center"" ss:WrapText=""1""/>")
    fs.WriteLine("    </ss:Style>")
    fs.WriteLine("  </ss:Styles>")

    ' Write the worksheet contents
    fs.WriteLine("<ss:Worksheet ss:Name=""Sheet1"">")
    fs.WriteLine("  <ss:Table>")
    For i As Integer = 0 To grdView.Columns.Count - 1
        fs.WriteLine(String.Format("    <ss:Column ss:Width=""{0}""/>", _
        grdView.Columns.Item(i).Width))
    Next
    fs.WriteLine("    <ss:Row>")
    For i As Integer = 0 To grdView.Columns.Count - 1
        fs.WriteLine(String.Format("      <ss:Cell ss:StyleID=""1"">" & _
            "<ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", _
            grdView.Columns.Item(i).HeaderText))
    Next
    fs.WriteLine("    </ss:Row>")

    ' Check for an empty row at the end due to Adding allowed on the DataGridView
    Dim subtractBy As Integer, cellText As String
    If grdView.AllowUserToAddRows = True Then subtractBy = 2 Else subtractBy = 1
    ' Write contents for each cell
    For i As Integer = 0 To grdView.RowCount - subtractBy
        fs.WriteLine(String.Format("    <ss:Row ss:Height=""{0}"">", _
            grdView.Rows(i).Height))
        For intCol As Integer = 0 To grdView.Columns.Count - 1
            cellText = grdView.Item(intCol, i).Value
            ' Check for null cell and change it to empty to avoid error
            If cellText = vbNullString Then cellText = ""
            fs.WriteLine(String.Format("      <ss:Cell ss:StyleID=""2"">" & _
                "<ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", _
                cellText.ToString))
        Next
        fs.WriteLine("    </ss:Row>")
    Next

    ' Close up the document
    fs.WriteLine("  </ss:Table>")
    fs.WriteLine("</ss:Worksheet>")
    fs.WriteLine("</ss:Workbook>")
    fs.Close()

    ' Open the file in Microsoft Excel
    ' 10 = SW_SHOWDEFAULT
    ShellEx(Me.Handle, "Open", myFile, "", "", 10)
End Sub

Private Sub exportExcel2(ByVal grdView As DataGridView, ByVal fileName As String, _
ByVal fileExtension As String, ByVal filePath As String)

    ' Choose the path, name, and extension for the Excel file
    Dim myFile As String = filePath & "\" & fileName & fileExtension

    ' Open the file and write the headers
    Dim fs As New IO.StreamWriter(myFile, False)
    fs.WriteLine("<html>")
    fs.WriteLine("<head></head>")
    fs.WriteLine("<body>")

    ' Write the worksheet contents
    fs.WriteLine("  <table>")
    For i As Integer = 0 To grdView.Columns.Count - 1
        fs.WriteLine(String.Format("    <cols width=""{0}""/>", _
        grdView.Columns.Item(i).Width))
    Next
    fs.WriteLine("    <tr>")
    For i As Integer = 0 To grdView.Columns.Count - 1
        fs.WriteLine(String.Format("      <td>" & _
            "{0}</td>", _
            grdView.Columns.Item(i).HeaderText))
    Next
    fs.WriteLine("    </tr>")

    ' Check for an empty row at the end due to Adding allowed on the DataGridView
    Dim subtractBy As Integer, cellText As String
    If grdView.AllowUserToAddRows = True Then subtractBy = 2 Else subtractBy = 1
    ' Write contents for each cell
    For i As Integer = 0 To grdView.RowCount - subtractBy
        fs.WriteLine(String.Format("    <tr height=""{0}"">", _
            grdView.Rows(i).Height))
        For intCol As Integer = 0 To grdView.Columns.Count - 1
            cellText = grdView.Item(intCol, i).Value
            ' Check for null cell and change it to empty to avoid error
            If cellText = vbNullString Then cellText = ""
            fs.WriteLine(String.Format("      <td>" & _
                "{0}</td>", _
                cellText.ToString))
        Next
        fs.WriteLine("    </tr>")
    Next

    ' Close up the document
    fs.WriteLine("  </table>")
    fs.WriteLine("</body>")
    fs.WriteLine("</html>")
    fs.Close()

    ' Open the file in Microsoft Excel
    ' 10 = SW_SHOWDEFAULT
    ShellEx(Me.Handle, "Open", myFile, "", "", 10)
End Sub


Excel 로 내보내는 방법 중 가장 간단한 방법은 COM(Microsoft.Office.Interop.Excel.Application)을 이용하는 방법이다. 하지만 임의로 제어해야 할 필요가 있다면. HTML 이나 XML 을 사용한 도큐멘트를 제작해도 Excel 은 인식이 가능하다.

위의 방법은 파일로 출력하는 방식. 다만 Excel 2007 기준에서 에러메시지를 하나 뱉는 경향이 있었다. (뭐.. 궁할때 쓰자;;)

2008/12/07 05:16 2008/12/07 05:16


태그 , ,

(go to top)

LazyDreamy » Computer/Programming

[VB] DataGridView 에서 Selected rows 가져오기

드림 | 2008/12/06 12:00

Private Function GetSelected(ByVal dataGridView As DataGridView) As List(Of DataRow)
    Dim list As New List(Of DataRow)()
    'If the dataGridView selected rows are null
    If dataGridView.SelectedRows Is Nothing OrElse dataGridView.SelectedRows.Count = 0 Then
        'Return list
        Return list
    End If
    For Each dataGridViewRow As DataGridViewRow In dataGridView.SelectedRows
        'Declare a null DataRow
        Dim dataRow As DataRow = Nothing
        Try
            'Declare a DataRowView(DataRowView)
            Dim dataRowView As DataRowView = DirectCast(dataGridViewRow.DataBoundItem, DataRowView)
            dataRow = dataRowView.Row
        Catch ex As Exception
            'Catch the exception
            'Write the error message
            System.Diagnostics.Debug.WriteLine("Error: " + ex.Message)
        End Try
        'If the row is null
        If dataRow Is Nothing Then
            'Continue
            Continue For
        End If
        'Add a row(DataRow) to list
        list.Add(dataRow)
    Next
    'Return list
    Return list
End Function


출처 : http://www.dreamincode.net/code/snippet2309.htm

2008/12/06 12:00 2008/12/06 12:00


태그 , ,

(go to top)

LazyDreamy » Computer/Programming

[VB] 파일 경로 추출

드림 | 2008/10/25 10:56

'디렉토리 취득
Console.WriteLine( _
    System.IO.Path.GetDirectoryName( _
        "C:\My Documents\My Pictures\Test.jpg"))
'결과: C:\My Documents\My Pictures

'확장자 취득
Console.WriteLine( _
    System.IO.Path.GetExtension( _
        "C:\My Documents\My Pictures\Test.jpg"))
'결과: .jpg

'파일명 취득
Console.WriteLine( _
    System.IO.Path.GetFileName( _
        "C:\My Documents\My Pictures\Test.jpg"))
'결과: Test.jpg

'확장자 없이 파일명 취득
Console.WriteLine _
    (System.IO.Path.GetFileNameWithoutExtension( _
        "C:\My Documents\My Pictures\Test.jpg"))
'결과: Test

'최상위 루트 취득
Console.WriteLine( _
    System.IO.Path.GetPathRoot( _
        "C:\My Documents\My Pictures\Test.jpg"))
'결과: C:\

출처 : http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=45&MAEULNo=18&no=380&ref=380


덧 : 프로그램 이름 및 실행 경로 받아오기

System.Reflection.Assembly.GetExecutingAssembly.Location

2008/10/25 10:56 2008/10/25 10:56


태그 ,

(go to top)