I have a program so user can switch and apply network configuration based on profile.
Public Shared Sub SetIP(ByVal nicName As String, ByVal IpAddresses As String, ByVal SubnetMask As String, ByVal gateway As String, ByVal dnsSearch1 As String, ByVal dnsSearch2 As String)
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
'Dim objMO As ManagementObject
For Each objMO As ManagementObject In objMOC
'Make sure this is enabled device. Not VMWare or memory card
If objMO("IPEnabled") Then
If (objMO("Caption").Equals(nicName)) Then
Dim objNewIP As ManagementBaseObject = objMO.GetMethodParameters("EnableStatic")
Dim objNewGate As ManagementBaseObject = objMO.GetMethodParameters("SetGateways")
Dim objNewDns As ManagementBaseObject = objMO.GetMethodParameters("SetDNSServerSearchOrder")
'Set DefaultGateway
objNewGate("DefaultIPGateway") = New String() {gateway}
objNewGate("GatewayCostMetric") = New Integer() {1}
'Set IPAddress and Subnet Mask
objNewIP("IPAddress") = IpAddresses.Split(","c) 'major changes
objNewIP("SubnetMask") = New String() {SubnetMask}
'Set DNS for only preferred
'objNewDns("DNSServerSearchOrder") = dnsSearch1.Split(","c)
'Dim setDns = objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDns, Nothing) 'comment jap
'try to set alternate here
Dim dns() As String = {dnsSearch1, dnsSearch2}
objNewDns("DNSServerSearchOrder") = dns
Dim setIP = objMO.InvokeMethod("EnableStatic", objNewIP, Nothing)
Dim setGateways = objMO.InvokeMethod("SetGateways", objNewGate, Nothing)
objMO.InvokeMethod("SetDNSServerSearchOrder", objNewDns, Nothing)
Exit For
End If
End If
Next
End Sub
By using WMI classes, right now WIFI adapter already set with 172.25.35.12 static IP address, and user want to switch to Ethernet which also will be using the same IP address.
After set with that IP, it will cause conflict where WIFI adapter is disabled. How can I solve the issues? Maybe I need to reset WIFI IP configuration at first..
Related
I want to send a file over the internet with a tcp connection. My code handles this for IpV4 well (creddits here go to http://technotif.com/creating-simple-tcpip-server-client-transfer-data-using-c-vb-net/, i just changed minor things to correct the file output)
I tried to use this with a friend of mine, but his router is uteer garbage, and it cant forward any ports whatsoever and wont even work with upnp. It is set to IpV6 as well, and as far as I know IPv6 doesnt need anymore port forwarding since every device has its own public ip.
sadly my program doesnt work with IPv6 adresses, and I have a hard time finding any information regarding this topic.
Here is my code:
Public Class Form1
Private nSockets As ArrayList
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim IPHost As IPHostEntry
IPHost = Dns.GetHostByName(Dns.GetHostName())
lblStatus.Text = "My IP address is " +
IPHost.AddressList(0).ToString()
nSockets = New ArrayList()
Dim thdListener As New Thread(New ThreadStart _
(AddressOf listenerThread))
thdListener.Start()
End Sub
Public Sub listenerThread()
Control.CheckForIllegalCrossThreadCalls = False
Dim tcpListener As New TcpListener(7080)
Dim handlerSocket As Socket
Dim thdstHandler As ThreadStart
Dim thdHandler As Thread
tcpListener.Start()
Do
handlerSocket = tcpListener.AcceptSocket()
If handlerSocket.Connected Then
lbConnections.Items.Add(
handlerSocket.RemoteEndPoint.ToString() +
"connected.")
SyncLock (Me)
nSockets.Add(handlerSocket)
End SyncLock
thdstHandler = New ThreadStart(AddressOf _
handlerThread)
thdHandler = New Thread(thdstHandler)
thdHandler.Start()
End If
Loop
End Sub
Public Sub handlerThread()
Dim handlerSocket As Socket
handlerSocket = nSockets(nSockets.Count - 1)
Dim networkStream As NetworkStream = New _
NetworkStream(handlerSocket)
Dim blockSize As Int16 = 16
Dim thisRead As Int16
Dim dataByte(blockSize) As Byte
SyncLock Me
' Only one process can access the
' same file at any given time
Dim fileStream As Stream
fileStream = File.OpenWrite("C:\Whatever.file")
While (True)
thisRead = networkStream.Read(dataByte,
0, dataByte.Length)
fileStream.Write(dataByte, 0, thisRead)
If thisRead = 0 Then Exit While
End While
fileStream.Close()
networkStream.Close()
End SyncLock
lbConnections.Items.Add("File Written")
handlerSocket = Nothing
End Sub
How do i make it IPv6 capable?
Forgot to put in my client, what do i have to change here to make it work? Since even with the changes to my server, its still not connecting properly.
Private Sub Sendfile()
Dim filebuffer As Byte()
Dim fileStream As Stream
fileStream = File.OpenRead(tbFilename.Text)
' Alocate memory space for the file
ReDim filebuffer(fileStream.Length)
fileStream.Read(filebuffer, 0, fileStream.Length)
' Open a TCP/IP Connection and send the data
Dim clientSocket As New TcpClient(tbServer.Text, 7080)
Dim networkStream As NetworkStream
networkStream = clientSocket.GetStream()
networkStream.Write(filebuffer, 0, fileStream.Length)
networkStream.Close()
End Sub
Your listener is currently listening to IPv4-address 0.0.0.0, which is the default when you only specify a port to the listener.
You need to use the TcpListener(IPAddress, Integer) overload and specify IPv6Any to listen to IPv6-addresses.
Dim tcpListener As New TcpListener(IPAddress.IPv6Any, 7080)
As a side note you should rather use a List(Of T) than an ArrayList. The latter is typeless and not as optimized for .NET as the former.
As you can see here I block the directory called "cleo". If I have it in my folder I can't click connect. How can I check if, for example, "Cleo", "Images", "Logs" exist in browsed file. I don't think making multiple If statements would be good, is there any other way?
Private Sub connect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connect.Click
Dim cleoPath As String
Dim filePath As String
filePath = System.IO.Path.Combine(TextBox2.Text, "gta_sa.exe")
cleoPath = System.IO.Path.Combine(TextBox2.Text, "cleo")
If File.Exists(filePath) Then
If Directory.Exists(cleoPath) Then
MsgBox("Pronasli smo cleo fajl u vasem GTA root folderu. Da se konektujete na server morate ga obrisati.")
Else
Dim p() As Process
p = Process.GetProcessesByName("samp")
If p.Count > 0 Then
MsgBox("Vec imate pokrenut SAMP - ugasite ga.")
Else
Try
Dim prozess As Process = Process.GetProcessesByName("samp")(0)
prozess.Kill()
Catch ex As Exception
End Try
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\SAMP", "PlayerName", TextBox1.Text)
Process.Start("samp://193.192.58.55:7782")
Dim client As New TcpClient
client.Connect("193.192.58.55", 10924)
Dim sendbytes() As Byte = System.Text.Encoding.ASCII.GetBytes(TextBox1.Text)
Dim stream As NetworkStream = client.GetStream()
stream.Write(sendbytes, 0, sendbytes.Length)
End If
End If
Else
MsgBox("Da se konektujete morate locirati GTA San Andreas folder.")
End If
End Sub
End Class
You could use extension methods combined with a directoryinfo to check if any of a list of directory exists. Depending of if you just want a true/false return or if you need to process each directories (for instance, by adding a custom message with the name of the folders that prevent your application from continuing.
Public Module DirectoryInfoExt
<System.Runtime.CompilerServices.Extension()>
Public Function AnyExists(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As Boolean
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Any(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function GetExistingDirectories(DirInfo As IO.DirectoryInfo, ParamArray Directories As String()) As IEnumerable(Of String)
Dim MyPath As String = DirInfo.FullName.TrimEnd("\"c) & "\"
Return Directories.Where(Function(Dir) IO.Directory.Exists(MyPath & Dir))
End Function
End Module
An example the boolean return.
Dim BaseDirectory As String = "C:\Games\GTA"
Dim GamePath As New DirectoryInfo(BaseDirectory)
' Will not give the specific path that exists, only a Boolean if any of theses folder are found
Dim ModsFound As Boolean = GamePath.AnyExists("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
If Not ModsFound Then
'Connect
Else
' Do something
End If
An example using the list return to generate a custome message prompt stating the name of the specific folders found.
'This version gives a list instead.
Dim ModsFoundList As IEnumerable(Of String) = GamePath.GetExistingDirectories("Images", "Cleo", "Logs", "SomeFolder\Subfolder")
Dim HasMod As Boolean = ModsFoundList.Count > 0
If HasMod Then
EvilModdedUserPrompt(ModsFoundList)
Exit Sub
End If
' Here, since HasMod is false, we can proceed with connection.
' Do connection
As for the EvilModdedUserPrompt method
Public Sub EvilModdedUserPrompt(ModsFoundList As List(Of String))
Dim OutputMessage As New Text.StringBuilder
OutputMessage.AppendLine("The following mods have been detected on your system:")
For Each Moditem As String In ModsFoundList
OutputMessage.AppendFormat("- {0}", Moditem)
OutputMessage.AppendLine()
Next
MessageBox.Show(OutputMessage.ToString)
End Sub
I'm trying to interact with WMI through a vb.net program in order to make any machine that runs this program pull the IP settings and DNS server settings from DHCP for all network adapters with an IP.
The code I presently have works for DHCP without issue, but does not change DNS settings. The program compiles and executes without issue, but the DNS settings are not changing to be fetched automatically from DHCP.
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (Not CBool(objMO("IPEnabled"))) Then
Continue For
End If
Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
Dim objSetDNS As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableDHCP")
objSetIP = objMO.InvokeMethod("EnableDHCP", Nothing, Nothing)
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
objSetDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", Nothing, Nothing)
Catch ex As Exception
MessageBox.Show("Settings unchanged : " & ex.Message)
End Try
Next objMO
I'm so close to getting this solved, I just need help to figure out this last step.
You annoyingly have to do it through the registry, they didn't add WMI methods for it. Specifically (taken from here: https://gallery.technet.microsoft.com/7b1cec46-bdb8-4afc-b240-9789eefce6de) you need to set this key to null.
"HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\"
Below is your code with the necessary new sub inserted in
Const conKeyPath = "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
Public Sub Test()
Dim objMC As ManagementClass = New ManagementClass("Win32_NetworkAdapterConfiguration")
Dim objMOC As ManagementObjectCollection = objMC.GetInstances()
For Each objMO As ManagementObject In objMOC
If (Not CBool(objMO("IPEnabled"))) Then
Continue For
End If
Try
Dim objNewIP As ManagementBaseObject = Nothing
Dim objSetIP As ManagementBaseObject = Nothing
Dim objNewDNS As ManagementBaseObject = Nothing
Dim objSetDNS As ManagementBaseObject = Nothing
objNewIP = objMO.GetMethodParameters("EnableDHCP")
objSetIP = objMO.InvokeMethod("EnableDHCP", Nothing, Nothing)
objNewDNS = objMO.GetMethodParameters("SetDNSServerSearchOrder")
objSetDNS = objMO.InvokeMethod("SetDNSServerSearchOrder", Nothing, Nothing)
SetDNSAutomatically(objMO.GetPropertyValue("settingID"))
Catch ex As Exception
MessageBox.Show("Settings unchanged : " & ex.Message)
End Try
Next objMO
End Sub
Private Sub SetDNSAutomatically(ByVal settingID As String)
If settingID = String.Empty Then
Throw New ArgumentNullException("settingID")
End If
Dim _adapterKeyPath = String.Format("{0}\{1}", conKeyPath, settingID)
My.Computer.Registry.SetValue(_adapterKeyPath, "NameServer", String.Empty)
End Sub
I'm struggling to figure out how to go about adding an attachment to an e-mail in VB.NET. Here is my code so far and I'm not sure how to include the attachment. It's my first time working with the command prompt and the email system.
Imports System.Net.Mail
Module Module1
Sub Main()
Dim client As New SmtpClient
Dim email As New MailMessage
Dim seconds As Integer
Dim interval As Integer
Dim ip As String = 0
Dim counter As Integer
Dim desktop As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
input(seconds, interval, ip, counter)
ping(interval, ip, desktop, counter)
Console.WriteLine("Program successfully executed.")
Console.ReadLine()
End Sub
Sub input(ByRef seconds As Integer, ByRef interval As Integer, ByRef ip As String, ByRef counter As Integer)
Console.WriteLine("Please enter the amount of seconds you would like between pings.")
Console.WriteLine("Please enter no fewer than five seconds.")
seconds = Console.ReadLine()
Console.Clear()
interval = seconds * 1000
Console.WriteLine("Please enter the IP you will be pinging.")
ip = Console.ReadLine()
Console.Clear()
Console.WriteLine("How many times would you like to ping?")
counter = Console.ReadLine()
Console.Clear()
End Sub
Sub ping(ByVal interval As Integer, ByVal ip As String, ByVal desktop As String, ByRef counter As Integer)
Do Until counter = 0
Process.Start("CMD", "/c ping " & ip & " >> " & desktop & "\log.txt")
System.Threading.Thread.Sleep(interval)
counter = counter - 1
Loop
End Sub
Sub email(ByRef client As SmtpClient, ByRef email As MailMessage, ByVal desktop As String)
client.UseDefaultCredentials = False
client.Credentials = New Net.NetworkCredential("fakebusiness01#gmail.com", "*****")
client.Port = 587
client.EnableSsl = True
client.Host = "smtp.gmail.com"
email = New MailMessage()
email.From = New MailAddress("fakebusiness01#gmail.com")
email.To.Add("genericmail01#gmail.com")
email.Subject = "Ping Results"
email.IsBodyHtml = False
email.Body = "The pings were successful, attached is the ping log."
client.Send(email)
End Sub
End Module
You already have the property Attachments in your MailMessage object. You only need to check whether the file to be attached exists to avoid any exception, as below;
Dim sFile as String = "Full_File_Path"
Dim Attachment = New System.Net.Mail.Attachment(sFile)
If IO.File.Exists(sFile) Then _
email.Attachments.Add(Attachment)
In case you are attaching more than one files;
' Assuming AttachmentFiles is an ArrayList holding your files
Dim iCountFiles as integer
If AttachmentFiles IsNot Nothing Then
iCountFiles = AttachmentFiles.Count - 1
For index = 0 To iCountFiles
Dim Attachment = New System.Net.Mail.Attachment(AttachmentFiles(index))
If IO.File.Exists(AttachmentFiles(index)) Then _
email.Attachments.Add(Attachment)
Next
End If
I am using vb.net 2010 to develop my software. Also have crystal reports in my projects and things are working perfectly in my PC.
My problem is that I design the crystal report in my PC with wizard and my PC is not the server, then upload it to the server so it would be accessible to users. But when try to open report a connection problem to the database pops up. I know that is due to the connection property when I designed the reports in my PC.
How can I solve this problem.
It is showing the popup for giving userid and password. I want to give the server connection programatically.
i given the following code still it showing the popup
Private Sub CrystalReportViewer1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles CrystalReportViewer1.Load
Dim cryRpt As New ReportDocument
Dim crtableLogoninfos As New TableLogOnInfos
Dim crtableLogoninfo As New TableLogOnInfo
Dim crConnectionInfo As New ConnectionInfo
Dim CrTables As Tables
Dim CrTable As Table
cryRpt.Load("E:\ColorLab1\colorlab\colorlab\rpt_bill.rpt")
With crConnectionInfo
.ServerName = "MAHESH\SQLEXPRESS"
.DatabaseName = "cc"
.UserID = "erp"
.Password = "123"
End With
CrTables = cryRpt.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next
CrystalReportViewer1.RefreshReport()
End Sub
How can i solve this?
Add this code in the module(for common access)
Public Sub SetReportDb(ByVal ConnectionString As String, ByRef CrystalReportViewer As CrystalDecisions.Windows.Forms.CrystalReportViewer, ByRef reportDocument As ReportClass)
'Get SQL Server Details
Dim builder As New System.Data.Common.DbConnectionStringBuilder()
builder.ConnectionString = ConnectionString
Dim zServer As String = TryCast(builder("Data Source"), String)
Dim zDatabase As String = TryCast(builder("Initial Catalog"), String)
Dim zUsername As String = TryCast(builder("User ID"), String)
Dim zPassword As String = TryCast(builder("Password"), String)
Dim ciReportConnection As New ConnectionInfo
ciReportConnection.ServerName = zServer
ciReportConnection.DatabaseName = zDatabase
ciReportConnection.UserID = zUsername
ciReportConnection.Password = zPassword
'Assign data source details to tables
For Each table As Table In reportDocument.Database.Tables
table.LogOnInfo.ConnectionInfo = ciReportConnection
table.ApplyLogOnInfo(table.LogOnInfo)
Next
For Each subrep As ReportDocument In reportDocument.Subreports
For Each table As Table In subrep.Database.Tables
table.LogOnInfo.ConnectionInfo = ciReportConnection
table.ApplyLogOnInfo(table.LogOnInfo)
Next
Next
'Assign data source details to the report viewer
If CrystalReportViewer.LogOnInfo IsNot Nothing Then
Dim tlInfo As TableLogOnInfos = CrystalReportViewer.LogOnInfo
For Each tbloginfo As TableLogOnInfo In tlInfo
tbloginfo.ConnectionInfo = ciReportConnection
Next
End If
reportDocument.VerifyDatabase()
reportDocument.Refresh()
CrystalReportViewer.ReportSource = reportDocument
CrystalReportViewer.Refresh()
End Sub
Inside each crystal report viewer give the below code it will override the old connection with connectionstring
Private Sub CrystalReportViewer1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CrystalReportViewer1.Load
SetReportDb(My.Settings.colorlabConnectionString, CrystalReportViewer1, rpt_inwardreport1)
End Sub
So to put this into a proper answer:
Your first problem is solved by creating the same DSN on your server that you have on your PC.
Your second problem can be solved using code that looks something like this:
connection.DatabaseName = [DatabaseName]
connection.UserID = [UserID]
connection.ServerName = [ServerName]
connection.Password = [Password]
or
myCrystalReport.SetDatabaseLogon("myUsername", "myPassword","servername","dbname");
I know this post is a few years old, but after struggling with these same problems, I thought I would add a variation of Mahesh ML's routine for MS SQL 2016 server.
A three things to note:
SqlClient.SqlConnectionStringBuilder is used instead of DbConnectionStringBuilder
zSecurity (added) for Window's authentication instead of database user
reportDocument.DataSourceConnections(0).IntegratedSecurity = True is needed when Windows authentication is used
Public Sub SetReportSQL(ByVal ConnectionString As String,
ByRef CrystalReportViewer As CrystalDecisions.Windows.Forms.CrystalReportViewer,
ByRef reportDocument As ReportClass)
'Get SQL Server Details
Dim builder As New SqlClient.SqlConnectionStringBuilder
builder.ConnectionString = ConnectionString
Dim zServer As String = TryCast(builder("Data Source"), String)
Dim zDatabase As String = TryCast(builder("Initial Catalog"), String)
Dim zSecurity As Boolean = Boolean.TryParse(builder("Integrated Security"), zSecurity)
Dim zUsername As String = TryCast(builder("User ID"), String)
Dim zPassword As String = TryCast(builder("Password"), String)
Dim ciReportConnection As New ConnectionInfo
ciReportConnection.ServerName = zServer
ciReportConnection.DatabaseName = zDatabase
ciReportConnection.IntegratedSecurity = zSecurity
If zSecurity = False Then
ciReportConnection.UserID = zUsername
ciReportConnection.Password = zPassword
Else
reportDocument.DataSourceConnections(0).IntegratedSecurity = True
End If
'Assign data source details to tables
For Each table As Table In reportDocument.Database.Tables
table.LogOnInfo.ConnectionInfo = ciReportConnection
table.ApplyLogOnInfo(table.LogOnInfo)
Next
For Each subrep As ReportDocument In reportDocument.Subreports
For Each table As Table In subrep.Database.Tables
table.LogOnInfo.ConnectionInfo = ciReportConnection
table.ApplyLogOnInfo(table.LogOnInfo)
Next
Next
'Assign data source details to the report viewer
If CrystalReportViewer.LogOnInfo IsNot Nothing Then
Dim tlInfo As TableLogOnInfos = CrystalReportViewer.LogOnInfo
For Each tbloginfo As TableLogOnInfo In tlInfo
tbloginfo.ConnectionInfo = ciReportConnection
Next
End If
reportDocument.VerifyDatabase()
reportDocument.Refresh()
CrystalReportViewer.ReportSource = reportDocument
CrystalReportViewer.Refresh()
End Sub
Hi guys i got the answer
Private Sub rpt_billform_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.CrystalReportViewer1.LogOnInfo.Item(0).ConnectionInfo.ServerName = "MAHESH\SQLEXPRESS"
Me.CrystalReportViewer1.LogOnInfo.Item(0).ConnectionInfo.DatabaseName = "cc"
Me.CrystalReportViewer1.LogOnInfo.Item(0).ConnectionInfo.UserID = "erp"
Me.CrystalReportViewer1.LogOnInfo.Item(0).ConnectionInfo.Password = "123"
End Sub