Disable USB Device Programmatically - vb.net

I've got a HID device that I need to programmatically disable in VB.NET. I downloaded the WMICodeCreator, and used that to generate the code to ID my device, but the code creator doesn't give me access to any methods to disable the device (only query for it's status).
How to disable the device?
Imports System
Imports System.Management
Imports System.Windows.Forms
Namespace WMISample
Public Class MyWMIQuery
Public Overloads Shared Function Main() As Integer
Try
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_USBDevice WHERE DeviceID = 'USB\\VID_0596&PID_0586\\1B0033000251343439343037'")
For Each queryObj As ManagementObject in searcher.Get()
Console.WriteLine("-----------------------------------")
Console.WriteLine("Win32_USBDevice instance")
Console.WriteLine("-----------------------------------")
Console.WriteLine("DeviceID: {0}", queryObj("DeviceID"))
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try
End Function
End Class
End Namespace

Related

Handle exceptions in VB.NET SSIS script with WebClient (FTP download)

In SSIS I am using a VB.NET script task to download a file from an FTP folder.
The script is the following
Imports System
Imports System.Data
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Public Class ScriptMain
Public Sub Main()
Dim objWebClient As WebClient = New WebClient()
Dim strDownloadURL As String = "ftp://mydownloadhosting.com/myfolder/" + Dts.Variables("GetDate").Value.ToString() + "_daily.xml"
Dim strFileName As String = Dts.Variables("WorkingFile").Value.ToString()
Dim wp As WebProxy = New WebProxy("my.proxy.local", 1234)
objWebClient.Proxy = wp
objWebClient.Credentials = New System.Net.NetworkCredential("username", "password")
objWebClient.DownloadFile(strDownloadURL, strFileName)
Dts.TaskResult = Dts.Results.Success
End Sub
End Class
it works correctly but my target is to manage the exception, in particular to discriminate between:
file not found
all other problems (timeout, problem with proxy, ...)
I have made some research about how to manage exception with WebClient() and I have found these:
How to catch 404 WebException for WebClient.DownloadFileAsync
How do I check a WebClient Request for a 404 error
Handling two WebException's properly
which they give different forms of the following:
try
{
// try to download file here
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
// handle the 404 here
}
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
// handle name resolution failure
}
}
The main problem is that my code is in VB.NET and all the posted answered are written in C#, how can make a try/catch construct to handle an exception in my code?
An equivalent code in VB.NET is:
Try
' try to download file here
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
If DirectCast(ex.Response, HttpWebResponse).StatusCode = HttpStatusCode.NotFound Then
' // handle the 404 here
End If
ElseIf ex.Status = WebExceptionStatus.NameResolutionFailure Then
' handle name resolution failure
End If
End Try
Though the above/your code is for HTTP, not for FTP. FTP has different status codes.
For FTP, use:
FtpWebResponse and
FtpStatusCode.
For some FTP examples, see:
C#: How to check if file exists on FTP before FtpWebRequest
VB.NET: VB.net - see if remote file exists
There are many C# to VB.NET converters that you can refer to when you need to convert simple codes:
Telerik C#/VB.NET online code converter
Instant VB – Our C# to VB.NET Converter
The equivalent VB.NET code is:
Imports System
Imports System.Data
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.Net
Public Class ScriptMain
Public Sub Main()
Try
Dim objWebClient As WebClient = New WebClient()
Dim strDownloadURL As String = "ftp://mydownloadhosting.com/myfolder/" + Dts.Variables("GetDate").Value.ToString() + "_daily.xml"
Dim strFileName As String = Dts.Variables("WorkingFile").Value.ToString()
Dim wp As WebProxy = New WebProxy("my.proxy.local", 1234)
objWebClient.Proxy = wp
objWebClient.Credentials = New System.Net.NetworkCredential("username", "password")
objWebClient.DownloadFile(strDownloadURL, strFileName)
Dts.TaskResult = Dts.Results.Success
Catch ex As WebException
If ex.Status = WebExceptionStatus.ProtocolError Then
If (CType(ex.Response, HttpWebResponse)).StatusCode = HttpStatusCode.NotFound Then
'handle the 404 here
End If
ElseIf ex.Status = WebExceptionStatus.NameResolutionFailure Then
'handle name resolution failure
End If
Dts.TaskResult = Dts.Results.Failure
End Try
End Sub
End Class

Mutex not locking and using not releasing file handle

I am having problems getting a file handle to close properly. I have tried to use an additional Mutex to ensure only one thread has access to this file at a time.
As far as I understand it the Using construct should ensure that the file handle is released properly, and the Mutex should ensure that this code can only run in 1 thread at a time.
The error occurs when the logger is called multiple times in rapid succession.
The gethashcode was an attempt to verify that the mutex instance is the same.
Error Message:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
The process cannot access the file '****\LOG.log' because it is being used by another process.
Source:
Imports System.IO
Imports System.Net.Mail
Imports System.Threading
Public NotInheritable Class FileLogger
Private Shared ReadOnly _instance As New Lazy(Of FileLogger)(Function() New FileLogger(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)
Public LOG_LEVEL As Integer = 4
Public LEVELS As New Dictionary(Of Double, String)
Private Shared strFile As String = "LOG.log"
Public Shared FileLoc As New Mutex()
Public Shared ReadOnly Property getLogger() As FileLogger
Get
Return _instance.Value
End Get
End Property
Private Sub New()
Dim strFile As String = "yourfile.log"
LEVELS.Add(0, "FATAL ")
LEVELS.Add(1, "CRITICAL")
LEVELS.Add(2, "ERROR ")
LEVELS.Add(3, "INFO ")
LEVELS.Add(4, "DEBUG ")
LEVELS.Add(2.5, "WARNING ")
End Sub
Public Sub writeEntry(ByVal message As String, ByVal level As Double)
If level <= LOG_LEVEL Then
Dim log_str As String = String.Format("{0} - in: {3} - {1}: {2}", DateTime.Now.ToString, LEVELS(level), message, Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(log_str)
If level < 3 Then ' warning or greater write to file else just console
Console.WriteLine(FileLoc.GetHashCode())
FileLoc.WaitOne(Timeout.Infinite)
Using sw As StreamWriter = New StreamWriter(strFile, True) '<-- Debugger points to this line
sw.WriteLine(log_str)
End Using
FileLoc.ReleaseMutex()
End If
If level <= 2 Then 'if error or greater send email
FileLoc.WaitOne(Timeout.Infinite)
Dim mail As New MailMessage
mail.To.Add("email")
mail.From = New MailAddress("email")
mail.Subject = "Error on MC Server (SERVERNAME)"
mail.Body = log_str
mail.IsBodyHtml = True
mail.Attachments.Add(New Attachment(strFile))
Dim smtp As New SmtpClient
smtp.Host = "IPADDR"
smtp.Send(mail)
FileLoc.ReleaseMutex()
End If
End If
End Sub
End Class
The email section was not closing the file correctly. wrapping this in a using construct fixed the issue.
I also ended up implementing the SyncLock construct around the entire operation.
as some of the comments have pointed out the mutex may or may not have been doing what it was supposed to, but the file handle was still open from the attachment operation.
Public Sub writeEntry(ByVal message As String, ByVal level As Double)
SyncLock FileLoc
If level <= LOG_LEVEL Then
Dim log_str As String = String.Format("{0} - in: {3} - {1}: {2}", DateTime.Now.ToString, LEVELS(level), message, Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(log_str)
If level < 3 Then ' warning or greater write to file else just console
Console.WriteLine(FileLoc.GetHashCode())
Using sw As StreamWriter = New StreamWriter(strFile, True)
sw.WriteLine(log_str)
End Using
End If
If level <= 2 Then 'if error or greater send email
Using at As Attachment = New Attachment(strFile)
Dim mail As New MailMessage
mail.To.Add("email")
mail.From = New MailAddress("email")
mail.Subject = "Error on MC Server (servername)"
mail.Body = log_str
mail.IsBodyHtml = True
mail.Attachments.Add(at)
Dim smtp As New SmtpClient
smtp.Host = "IPADDR"
smtp.Send(mail)
End Using
End If
End If
End SyncLock
End Sub

Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute is not defined

Using a script I found here Problem is it's for 2012 and I'm using 2008.
I've handled all of the personal stuff(connections, variables, URLS, etc.) But I keep getting an error when I try to run the script.
Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute is not defined
Using VB.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.ComponentModel
Imports System.Diagnostics
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
Partial Public Class ScriptMain
Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
Enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
End Enum
Protected Sub SaveFile(ByVal url As String, ByVal localpath As String)
Dim loRequest As System.Net.HttpWebRequest
Dim loResponse As System.Net.HttpWebResponse
Dim loResponseStream As System.IO.Stream
Dim loFileStream As New System.IO.FileStream(localpath, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim laBytes(256) As Byte
Dim liCount As Integer = 1
Try
loRequest = CType(System.Net.WebRequest.Create(url), System.Net.HttpWebRequest)
loRequest.Credentials = System.Net.CredentialCache.DefaultCredentials
loRequest.Timeout = 600000
loRequest.Method = "GET"
loResponse = CType(loRequest.GetResponse, System.Net.HttpWebResponse)
loResponseStream = loResponse.GetResponseStream
Do While liCount > 0
liCount = loResponseStream.Read(laBytes, 0, 256)
loFileStream.Write(laBytes, 0, liCount)
Loop
loFileStream.Flush()
loFileStream.Close()
Catch ex As Exception
End Try
End Sub
Public Sub Main()
Dim url, destination As String
destination = Dts.Variables("Folder_Destination").Value.ToString + "\" + "Report_" + Dts.Variables("ReportParameter").Value.ToString + "_" + Format(Now, "yyyyMMdd") + ".xls"
url = "http://localhost:8080/ReportServer?/MyReports/SSIS_Execute_SSRS_Report&rs:Command=Render&Productkey=" + Dts.Variables("ReportParameter").Value.ToString + "&rs:Format=EXCEL"
SaveFile(url, destination)
Dts.TaskResult = ScriptResults.Success
End Sub
End Class
Figured it out.
The Addin.Addins have been deprecated.
<Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> _
<System.CLSCompliantAttribute(False)> _
is fine for 2010 but for 2008
<System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
<System.CLSCompliantAttribute(False)> _
is needed.
Hope that helps anyone else out.
I got the same error message trying to import an existing SSIS 2016 package into a new solution.
I found that when I created my new solution in VS/TFS it set the target server version to 2017.
I changed the TargetServerVersion back to 2016 and it now works.
In VS, Right click on Project > view Properties.
Look under Configuration properties > General > TargetServerVersion.

How to modify existing REST web service to work with SSL

I have the following simple REST service running based on the code found on MSDN - code below.
How can I modify this to be able to use transport security - SSL ?
I've been googling around for a solution, but it seems that most examples are mentioning to modify web.config file, but this example doesn't even have that... Thanks for any help with this one!
Imports System
Imports System.Collections.Generic
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Web
Imports System.Text
<ServiceContract()> _
Public Interface IService
<OperationContract()> _
<WebGet()> _
Function EchoWithGet(ByVal s As String) As String
<OperationContract()> _
<WebInvoke()> _
Function EchoWithPost(ByVal s As String) As String
end interface
Public Class Service
Implements IService
Public Function EchoWithGet(ByVal s As String) As String Implements IService.EchoWithGet
Return "You said " + s
End Function
Public Function EchoWithPost(ByVal s As String) As String Implements IService.EchoWithPost
Return "You said " + s
End Function
End Class
Module program
Sub Main()
Dim host As WebServiceHost = New WebServiceHost(GetType(Service), New Uri("http://localhost:8000/"))
Try
Dim ep As ServiceEndpoint = host.AddServiceEndpoint(GetType(IService), New WebHttpBinding(), "")
host.Open()
Using cf As New ChannelFactory(Of IService)(New WebHttpBinding(), "http://localhost:8000")
cf.Endpoint.Behaviors.Add(New WebHttpBehavior())
Dim channel As IService = cf.CreateChannel()
Dim s As String
Console.WriteLine("Calling EchoWithGet via HTTP GET: ")
s = channel.EchoWithGet("Hello, world")
Console.WriteLine(" Output: {0}", s)
Console.WriteLine("")
Console.WriteLine("This can also be accomplished by navigating to")
Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!")
Console.WriteLine("in a web browser while this sample is running.")
Console.WriteLine("")
Console.WriteLine("Calling EchoWithPost via HTTP POST: ")
s = channel.EchoWithPost("Hello, world")
Console.WriteLine(" Output: {0}", s)
Console.WriteLine("")
End Using
Console.WriteLine("Press <ENTER> to terminate")
Console.ReadLine()
host.Close()
Catch cex As CommunicationException
Console.WriteLine("An exception occurred: {0}", cex.Message)
host.Abort()
End Try
End Sub
End Module
Adding the following solved my problem and all traffic goes through HTTPS. I hope this will help someone in the future.
Dim binding As New WebHttpBinding
binding.Security.Mode = WebHttpSecurityMode.Transport
Dim store As New X509Store(StoreName.My, StoreLocation.LocalMachine)
store.Open(OpenFlags.ReadWrite)
Dim cert = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", False)(0)
store.Close()
Dim bindPortToCertificate As New Process
bindPortToCertificate.StartInfo.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "netsh.exe")
bindPortToCertificate.StartInfo.Arguments = String.Format("http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={{{2}}}", 22370, cert.Thumbprint, Guid.NewGuid())
bindPortToCertificate.Start()
bindPortToCertificate.WaitForExit()

Declaration expected in VB dll

First of all thanking everyone....
I am currently working on VB. I am using Visual Studio 2008.
The piece of code below is a console application which builds without any error.
Imports System.Net
Module Module1
Public Sub Main()
Dim address As IPAddress
Dim remoteIP As System.Net.IPEndPoint
Dim socketAddress As System.Net.SocketAddress
Try
address = IPAddress.Parse("192.168.0.187")
remoteIP = New System.Net.IPEndPoint(address, 0)
socketAddress = remoteIP.Serialize()
Console.WriteLine("Address Family :" & remoteIP.AddressFamily.ToString())
Console.WriteLine("IP :" & remoteIP.Address.ToString() & "Port :" & remoteIP.Port.ToString())
Console.WriteLine("Socket address :" & socketAddress.ToString())
Catch ex As Exception
Console.WriteLine(ex.StackTrace.ToString())
End Try
End Sub
End Module
In the next program which is a dll the same gives error saying "Declaration Expected for addr, remoteIP and socketAddr"
Imports System.Net
Public Class Class1
End Class
Public Class ethernet
Dim addr As IPAddress
Dim remoteIP As System.Net.IPEndPoint
Dim socketAddr As System.Net.SocketAddress
addr = IPAddress.Parse("192.168.0.187")
remoteIP = New System.Net.IPEndPoint(addr,0)
socketAddr = remoteIP.Serialize()
End Class
Can anybody tell me why is this happening...
Your code in the second class ethernet is not contained within a Method, therefore you are only declaring the addr, remoteIP and socketAddr variables.
To make that work just put the code in a method, like:
Public Class ethernet
Public Function SerializeSocket(address As String) As System.Net.SocketAddress
Dim addr As IPAddress = IPAddress.Parse("192.168.0.187")
Dim remoteIP As System.Net.IPEndPoint = New System.Net.IPEndPoint(addr,0)
Return remoteIP.Serialize()
End Sub
End Class