- 2010/03/07 .NET Socket Programming (for data arriving event) (1)
- 2009/02/08 [VB.Net] 시스템 내부 고유 값 알아오기. (2)
- 2008/12/07 [VB] INI Read / Write (3)
- 2008/12/07 [VB] Datagrid to Excel export
- 2008/12/06 [VB] DataGridView 에서 Selected rows 가져오기 (1)
- 2008/10/25 [VB] 파일 경로 추출
LazyDreamy » Search » Results » Articles
VB.NET와 관련된 글 6개
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 'StateObjectPublic 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.EmptyPublic 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 'MainPrivate 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 'ConnectCallbackPrivate 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 'ReceivePrivate 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 'ReceiveCallbackPrivate 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 'SendPrivate 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 내장 함수를 사용하려고 찾다 보니 소켓 이벤트 형태를 지원한다.
트랙백 없음 | 댓글 1개
트랙백+댓글 | 트랙백 | 댓글
-
Comment by 드림 at 2010/03/19 23:31 / Permalink / Reply / Modify/Delete
socket with Thread
http://vb.net-informations.com/communications/vb.net_chat_client.htm -
Write your comment
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 FunctionGetVolumeSerialNumber("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 StringPublic 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 FunctionPublic 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 ExceptionEnd Try
Catch ex As ExceptionEnd Try
Next
End Sub
코드는 여기저기서 참고하고 짜집은 상태라 너덜너덜하며 –_-;;
특히 NIC 관련해서는 2개 이상 연결도 고려해야 하지만.. 과감히 패스!;
연결에서 찾아진 MAC Address 로 IP Address 와 DESC 정보 알아오는 부분 추가
트랙백 없음 | 댓글 2개
트랙백+댓글 | 트랙백 | 댓글
-
Comment by 드림 at 2009/02/08 09:09 / Permalink / Reply / Modify/Delete
strComputer = "."
strTargetAddress = "192.59.244.247"
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = True")
For Each objItem in colItems
arrIPAddresses = objItem.IPAddress
For Each strAddress in arrIPAddresses
If strAddress = strTargetAddress Then
strMACAddress = objItem.MacAddress
End If
Next
Next
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_NetworkAdapter Where MACAddress = '" & strMACAddress & "'")
For Each objItem in colItems
If Not IsNull(objItem.NetConnectionID) Then
Wscript.Echo objItem.NetConnectionID
End If
Next
http://www.microsoft.com/technet/scriptcenter/resources/qanda/jun05/hey0614.mspx -
Comment by 드림 at 2009/02/08 09:09 / Permalink / Reply / Modify/Delete
방식 고민 중;;
-
Write your comment
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 LongPublic 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 FunctionPublic Function INIWrite(ByVal Session As String, ByVal KeyValue As String, ByVal DataValue As String, ByVal INIFILE As String) As String
'INI 값 기록
Dim ReturnValue As LongReturnValue = WritePrivateProfileString(Session, KeyValue, DataValue, INIFILE)
End FunctionPublic Sub SetInifile()
Dim path As String = getMyPath()
Dim filename As String = getMyFilename()'Setup.ini 세팅
INIFILE = path & "\" & filename & ".ini"
End SubPublic Function getMyPath() As String
Return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location)
End FunctionPublic 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 가 제 맛..;;
프로그램이 갈수록.. 파서 덩어리가 되가네 –_-;;;
트랙백 없음 | 댓글 3개
트랙백+댓글 | 트랙백 | 댓글
-
Comment by 드림 at 2008/12/07 11:28 / Permalink / Reply / Modify/Delete
참고 :
http://www.myhome.pe.kr/zbxe/vb/888/page/1
http://down.file.naver.com/howpc/kin.nhn?m=read§ion=read&docid=7980737&page=1315
http://www.mandki.com/bbs/board.php?bo_table=mandki&wr_id=496&sfl=&stx=&sst=wr_good&sod=desc&sop=and&page=8 -
Comment by 드림 at 2010/03/19 23:29 / Permalink / Reply / Modify/Delete
http://www.developer.com/net/asp/article.php/3287991/INI-Files-Will-Never-Die-How-To-in-NET.htm
-
Comment by 드림 at 2010/03/25 00:51 / Permalink / Reply / Modify/Delete
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
함수의 버그
str = str.Substring(0, Len(str) - 1)
str = Trim(str)
를
str = Trim(str)
str = str.Substring(0, Len(str) - 1)
순서로 해줘야 함 -
Write your comment
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 SubPrivate 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 기준에서 에러메시지를 하나 뱉는 경향이 있었다. (뭐.. 궁할때 쓰자;;)
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
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























