How can I determine IP address of a workstation logged into a windows server from vb6 code - sql-server-2008-r2

I have a VB6 program that is multi-user and runs on a network. Some users are on Windows XP Desktops and some are on Thin clients logging in to a Windows 2008R2 Server using RDP. I have a new requirement which requires that I know the IP addresses of the users on the Local Area Network, and the IP of the remote users, or the login of the remote users. I am not sure this is even possible. Any help or information would be greatly appreciated.

This returns current RDP session's client IP address or an empty string when not executed under RDP session.
Client IP address is one of the local IPs of the client machine as reported by the mstsc.exe upon establishing connection and might differ from the real IPs observed with netstat or similar.
Option Explicit
'--- for WTSQuerySessionInformation
Private Const WTS_CURRENT_SERVER_HANDLE As Long = 0
Private Const WTS_CURRENT_SESSION As Long = -1
Private Const WTSClientAddress As Long = 14
'--- for AddressFamily
Private Const AF_INET As Long = 2
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)
Private Declare Function WTSQuerySessionInformation Lib "wtsapi32" Alias "WTSQuerySessionInformationA" (ByVal hServer As Long, ByVal SessionId As Long, ByVal WtsInfoClass As Long, ppBuffer As Long, pBytesReturned As Long) As Long
Private Declare Sub WTSFreeMemory Lib "wtsapi32" (ByVal pMemory As Long)
Private Type WTS_CLIENT_ADDRESS
AddressFamily As Long
Address(0 To 19) As Byte
End Type
Private Function GetSessionClientIp() As String
Dim uAddress As WTS_CLIENT_ADDRESS
Dim lPtr As Long
Dim lSize As Long
Call WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSClientAddress, lPtr, lSize)
If lSize >= LenB(uAddress) Then
Call CopyMemory(uAddress, ByVal lPtr, LenB(uAddress))
End If
Call WTSFreeMemory(lPtr)
If uAddress.AddressFamily = AF_INET Then
GetSessionClientIp = uAddress.Address(2) & "." & uAddress.Address(3) & "." & uAddress.Address(4) & "." & uAddress.Address(5)
End If
End Function
Private Sub Form_Load()
MsgBox "GetSessionClientIp=" & GetSessionClientIp(), vbExclamation
End Sub

Related

Ms Access - Button with code doesn't work to send email

I have this code set in access, but no email is sending upon clicking the button on the form. I have outlook open. When i click the button on the form, i can't see anything that actually happens. I want the email address to be equal to the value in [text1], and I am trying to make the subject include a fixed message plus the input from [text2]. Even without these variables, I can't get this to work
Public Sub Command495_Click()
Dim mailto As String
Dim ccto As String
Dim bccto As String
mailto = [text1]
ccto = ""
bccto = ""
emailmsg = "trial"
mailsub = [text2] & ", Does this work?"
On Error Resume Next
DoCmd.SendObject acSendNoObjectType, , acFormattxt, mailto, ccto, bccto, mailsubj, emailmsg, True
End Sub
I have checked to make sure the onclick property shows event procedure. I am stuck, please help!
Here are a few suggestions and a modified version of your code.
ALWAYS use Option Explicit and compile your module before testing. You had a number of variables that were not defined and incorrect spelling of some options.
NEVER bypass errors when testing (get rid of your "On Error Resume Next") That's why you never saw an error.
Look for every place I entered ">>>" and address that issue.
Always explicitly define your variables and use the proper Type. Removes all doubt of what/where something is.
Option Compare Database
Option Explicit
Public Sub Command495_Click()
Dim mailto As String
Dim ccto As String
Dim bccto As String
Dim emailmsg As String
Dim mailsub As String
mailto = [Text1] ' >>> Where is [Text1]?? Remove for testing
ccto = ""
bccto = ""
emailmsg = "trial"
mailsub = [Text2] & ", Does this work?" ' >>> Where is [Text2]?? Remove for testing
' >>> Bad idea to ignore errors when testing!!
On Error Resume Next
'>>> Following line had: (1) 'acSendNoObjectType' which is incorrect; (2) mailsubj, which is undefined
DoCmd.SendObject acSendNoObject, , acFormatTXT, mailto, ccto, bccto, mailsub, emailmsg, True
End Sub

Passing value into your parameter (rs.exe) by stored procudure

I have a situation here where I have a deployed rdl file in the reporting server. The rdl file in question has a parameter.
I am using the rs.exec component to execute the report; whenever I remove the parameter from the rdl file, I successfully run the report from the stored procedure. When I add the parameter, all I keep getting is
\\server\R\subfolder\working\inputfile\example.batK00WE is not recognized as an internal or external operable program or batch file.
Here is what I did: I created a .rss file in VB (Please see code below)
Public Sub Main()
TRY
DIM historyID as string = Nothing
DIM deviceInfo as string = Nothing
DIM extension as string = Nothing
DIM encoding as string
DIM mimeType as string = "application/Excel"
DIM warnings() AS Warning = Nothing
DIM streamIDs() as string = Nothing
DIM results() as Byte
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
rs.LoadReport(REPORTSERVER_FOLDER, historyID)
results = rs.Render(FORMAT, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
DIM stream As FileStream = File.OpenWrite(FILENAME)
stream.Write(results, 0, results.Length)
stream.Close()
Catch e As IOException
Console.WriteLine(e.Message)
End Try
End Sub
Afterwards... I wrote batch file that utilizes the rs.exec. Please see below:
"\\server\R\subfolder\working\app\rs.exe" -i \\server\R\subfolder\working\inputfile\coo.rss -s "http://server/ReportServer_MSSQLSERVER2" -v FILENAME="\\server\R\subfolder\working\inputfile\file.csv" -v REPORTSERVER_FOLDER="/FILE_REPORT/FILE" -t -v FORMAT="EXCEL" -e Exec2005
If you see the above script the rs.exec utilizes the path of the report server etc.
Finally I created a stored procedure that will run the report on the server and pass into the server the parameter value.
CREATE PROCEDURE [dbo].[test_sproc]
#ProcessID varchar(50)
AS
DECLARE #cmdsql varchar(1000)
Declare #id varchar(50)
Set #id=#SID
Set #cmdsql= '"\\server\R\subfolder\working\inputfile\example.bat"' + #id
exec master..xp_CMDShell #cmdsql
So here is my question is: How do I pass the parameter value from stored procedure to the report server? Where did I go wrong with my code?

Create User Defined Type In SMO

How Create User Defined Type (ex: Point(X int,Y int) With SMO?
I Am Use VB.NET (Or C#.NET) And Want Use SMO For Create?
I know must use "UserDefinedType" in SMO but i don't know How?!
Thanks.
By using following code sample you can create UserDefinedType using SMO:
Dim oServer As Microsoft.SqlServer.Management.Smo.Server
Dim oSMOServer As Microsoft.SqlServer.Management.Smo.Server
Dim oSMODatabase As Microsoft.SqlServer.Management.Smo.Database
Dim sUDT As String = "udt_RecordID"
Try
oServer = New Microsoft.SqlServer.Management.Smo.Server()
''Set ServerName
oServer.ConnectionContext.ServerInstance = pServerInstanceName
''Set is Windows Authentication
oServer.ConnectionContext.LoginSecure = pIsWinAuth
''Set Server UserName & Password, If not Windows Authentication
If pIsWinAuth = False Then
oServer.ConnectionContext.Login = pUsername
oServer.ConnectionContext.Password = pPassword
End If
Dim oUDTs = oSMOServer.Databases(pDatabaseName).UserDefinedTableTypes
''Add UserDefinedType if not exist
If Not oUDTs.Contains(sUDT) Then
oSMODatabase = oSMOServer.Databases(pDatabaseName)
Dim udtt As UserDefinedTableType
udtt = New UserDefinedTableType(oSMODatabase, sUDT)
''Add necessary columns
udtt.Columns.Add(New Microsoft.SqlServer.Management.Smo.Column(udtt, "RecordID", DataType.NVarChar(50)))
''Create UserDefinedType
udtt.Create()
End If
Catch ex As Exception
''Handle Exception
End Try
Feel free to ask if required.

Form creation Error after server checkpoint passed

I'm making a server checkpoint in my new version for this app. and I'm encountering this error
when my app tries to open my main form.
An error occurred creating the form. See Exception.InnerException for
details. The error is: ActiveX control
'6bf52a52-394a-11d3-b153-00c04f79faa6' cannot be instantiated because
the current thread is not in a single-threaded apartment.
I'm not sure what this is, because it's something like a usual form except this form is used as Splash screen. When I remove the splash screen the form opens normally with all plugins and modules.
Here's a part of the code I used
Public Class example_form
Public Function servercheck() As Boolean
Dim objUrl As New System.Uri("http://google.com")
Dim objWebReq As System.Net.WebRequest
objWebReq = System.Net.WebRequest.Create(objUrl)
Dim objresp As System.Net.WebResponse
Try
objresp = objWebReq.GetResponse
objresp.Close()
objresp = Nothing
Return True
Catch ex As Exception
objresp = Nothing
objWebReq = Nothing
Return False
End Try
End Function
Private Sub Form4_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
BackgroundWorker1.RunWorkerAsync()
Control.CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If servercheck() = True Then
Form1.Show()
Me.Hide()
BackgroundWorker1.CancelAsync()
Else : PictureBox1.Image = My.Resources._12383u9
MsgBox("some text here", MsgBoxStyle.Critical)
End
End If
End Sub
End Class
Now you have the code. The error is on the background worker when it tries to open the form. (at the end of the code)
Ok i found what is the error. For those who have this error, do not add the form.show() command in the backgroundworker in work mode. the form should be load when backgroundworker will finish. so the correct code is like this
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If servercheck() = True Then
Me.Hide()
BackgroundWorker1.CancelAsync()
Else : PictureBox1.Image = My.Resources._12383u9
MsgBox("Some text here", MsgBoxStyle.Critical)
End
End If
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Form1.Show()
End Sub

Follow up about using VBA to send e-mail

This is a follow up to several messages about using VBA to send e-mail.
Most suggestions use either Outlook, CDO, or MAPI:
Set appOL = CreateObject("Outlook.Application")
Set msgOne = CreateObject("CDO.Message")
Set mapi_session = New MSMAPI.MAPISession
But apparently Outlook will require me to change our workgroup security settings, and CDO and MAPI will require me to add a DLL or something.
I'm trying to use Excel to organize group assignments at work and I can't modify the other people's computers in any way.
Is there a simpler way to send e-mails from an Excel macro?
All I need is a block of text in the body of the message with no attachments.
I've been plowing through Google, MSDN & StackOverflow all week and I'm stuck on a slow boat to nowhere.
Building up on what Marc mentioned, Here is a tried and tested version.
Option Explicit
Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, _
ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, _
ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Sub SendMail()
Dim objMail As String
Dim oMailSubj, oMailTo, oMailBody As String
On Error GoTo Whoa
oMailSubj = "YOUR SUBJECT GOES HERE"
oMailTo = "ABC#ABC.COM"
oMailBody = "BLAH BLAH!!!!"
objMail = "mailto:" & oMailTo & "?subject=" & oMailSubj & "&body=" & oMailBody
ShellExecute 0, vbNullString, objMail, vbNullString, vbNullString, vbNormalFocus
Application.Wait (Now + TimeValue("0:00:03"))
Application.SendKeys "%s"
Exit Sub
Whoa:
MsgBox Err.Description
End Sub
FOLLOWUP
Thanks for the info. I had already ruled out ShellExecute because it limits the entire parameter string to 250 char and I need about 2000 for the message. But it's looking like SE is the only option that will actually work in my case. – Humanoid1000 7 hours ago
Here is the "Horrible (I love the way JFC says that!!!)" way I mentioned below in the comments which works beautifully :) BTW I have only Outlook as my default client so I have tested it with that.
CODE
Option Explicit
Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, _
ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, _
ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub SendMail()
Dim objMail As String
Dim oMailSubj As String, oMailTo As String
Dim i As Long
Dim objDoc As Object, objSel As Object, objOutlook As Object
Dim MyData As String, strData() As String
On Error GoTo Whoa
'~~> Open the txt file which has the body text and read it in one go
Open "C:\Users\Siddharth Rout\Desktop\Sample.Txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
Sleep 300
oMailSubj = "YOUR SUBJECT GOES HERE"
oMailTo = "ABC#ABC.COM"
objMail = "mailto:" & oMailTo & "?subject=" & oMailSubj
ShellExecute 0, vbNullString, objMail, vbNullString, vbNullString, vbNormalFocus
Sleep 300
Set objOutlook = GetObject(, "Outlook.Application")
'~~> Get a Word.Selection from the open Outlook item
Set objDoc = objOutlook.ActiveInspector.WordEditor
Set objSel = objDoc.Windows(1).Selection
objDoc.Activate
Sleep 300
For i = LBound(strData) To UBound(strData)
objSel.TypeText strData(i)
objSel.TypeText vbNewLine
Next i
Set objDoc = Nothing
Set objSel = Nothing
'~~> Uncomment the below to actually send the email
'Application.Wait (Now + TimeValue("0:00:03"))
'Application.SendKeys "%s"
Exit Sub
Whoa:
MsgBox Err.Description
End Sub
SNAPSHOT
Text File which has the message
Email just before it is sent
You can probably use the Shell command.
Shell("mailto:username#isp.com")
If Outlook is your default email program, I think windows will interpret that properly (it does it from the windows RUN dialog, but not sure if from VBA). Try it out. I'm not in front of Excel at the moment.
Review the params for "mailto" to see how you can add subject and body to that string.
CORRECTION:
That will only generate the email, but won't send it. Disregard my answer.
Here's the final result:
Turns out, the SendMail() worked at home but not at work, but CreateObject("Outlook.Application") did work at work.
My security settings were not the problem with Outlook, it was a mundane typo.
Either way, there's bunch of good info on this page for anyone else who's lost on this topic.