How to modify existing REST web service to work with SSL - vb.net

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()

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

Disable USB Device Programmatically

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

Socket program freezes on load

The program freezes on load. At first it was working as it was supposed to, but after I cleaned and built the solution, it only freezes on load. The weird part is that it only freezes and it does not show the exception message for the catch.
here is the class file I used
Imports System.Net ' for IPAddress
Imports System.Net.Sockets 'for TcpListener
Public Class clientSocket
Dim aString As String
Dim port As Integer 'this is the port number
Dim localAddr As IPAddress ' this is the IP address
Dim client As TcpClient ' This is for the TCP/IP Protocol
Dim clientListener As TcpListener
Public Function startSocket() As String
Try
'define the two values for your Server
port = 1234
localAddr = IPAddress.Loopback 'loopbak = 127.0.0.1 = myself
clientListener = New TcpListener(localAddr, 4321)
client = New TcpClient(localAddr.ToString, port)
Return "Connected to the server"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function receive() As String
Try
clientListener.Start()
Dim mySocket As Socket
mySocket = clientListener.AcceptSocket()
Dim recieveBuff(225) As Byte
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
Return str
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
str = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
clientListener.Stop()
Catch exp As Exception
Return "Exception: " + exp.Message
End Try
End Function
End Class
Or use BeginAcceptSocket, but you'll have to move your receive code to the callback.
mySocket = clientListener.AcceptSocket()
These lines block further action untill a socket has been acepted, it will block your code until a socket has been accepted. Use thread to prevent blocking

Importing Google Drive Quickstart Code to Visual Basic

I am trying to get the Quickstart code for .Net imported to Visual Basic (VB .NET) and I had some errors. I am a newbie to this kind of programming. Would appreciate some pointers, or someone pointing out something that is fundamentally wrong with the code.
Appreciate the help!
The errors that I get when I try to compile the Console App are:
Error 2 Argument not specified for parameter 'arg' of 'Private Shared Function GetAuthorization(arg As Google.Apis.Authentication.OAuth2.DotNetOpenAuth.NativeApplicationClient) As DotNetOpenAuth.OAuth2.IAuthorizationState'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 22 86 Nipod Drive Console
Error 3 'BaseClientService' is ambiguous in the namespace 'Google.Apis.Services'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 23 48 Nipod Drive Console
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports Google.Apis.Services
Namespace GoogleDriveSamples
Class DriveCommandLineSample
Shared Sub Main(ByVal args As String)
Dim CLIENT_ID As [String] = "YOUR_CLIENT_ID"
Dim CLIENT_SECRET As [String] = "YOUR_CLIENT_SECRET"
'' Register the authenticator and create the service
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthorization)
Dim service = New DriveService(New BaseClientService.Initializer() With { _
.Authenticator = auth _
})
Dim body As New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("document.txt")
Dim stream As New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
Console.WriteLine("File id: " + file.Id)
Console.WriteLine("Press Enter to end this process.")
Console.ReadLine()
End Sub
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState( New () {DriveService.Scopes.Drive.GetStringValue()})
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Console.Write(" Authorization Code: ")
Dim authCode As String = Console.ReadLine()
Console.WriteLine()
' Retrieve the access token by using the authorization code:
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
End Namespace
I reliase this is an old subject, but this may help someone in future, make sure you compile in framework 3.5
Sorry cant seem to edit or delete my previous answer, for anyone in future, this should help:
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports System.Security
Imports Google.Apis.Services
Public Class GoogleDrive
Public Function UploadFile() As Boolean
Const CLIENT_ID As String = "xxxxxxxxxxxxx.apps.googleusercontent.com"
Const CLIENT_SECRET As String = "-yyyyyyyyyyyyyyyyyyyyyyy"
'Register the authenticator and create the service
Dim provider As NativeApplicationClient = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim getAuth As Func(Of NativeApplicationClient, IAuthorizationState) = AddressOf GetAuthorization
Dim auth As OAuth2Authenticator(Of NativeApplicationClient) = New OAuth2Authenticator(Of NativeApplicationClient)(provider, getAuth)
Dim service = New DriveService(New BaseClientService.Initializer() With {.Authenticator = auth})
Dim body As File = New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("D:\document.txt")
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
MessageBox.Show("File : " & file.Id)
End Function
Private Function GetAuthorization(ByVal Client As NativeApplicationClient) As IAuthorizationState
Dim RetVal As IAuthorizationState
Dim state As IAuthorizationState = New AuthorizationState(New String() {DriveService.Scopes.Drive.GetStringValue()})
'Check to see if we have a saved refresh token
If My.Settings.SavedAuth.ToString <> "" Then
state.RefreshToken = My.Settings.SavedAuth
If (Client.RefreshToken(state)) Then
Return state
End If
End If
'Get the auth URL:
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = Client.RequestUserAuthorization(state)
'Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
'wait until user has entered the code
Dim authCode As String = InputBox("Authorisation code", "Authorisation Code", "")
'Retrieve the access token by using the authorization code:
RetVal = Client.ProcessUserAuthorization(authCode, state)
'store the refresh token
Call StoreRefreshToken(state.RefreshToken)
Return RetVal
End Function
Private Function LoadRefreshToken() As String
Return My.Settings.SavedAuth
End Function
Private Sub StoreRefreshToken(ByVal Token As String)
My.Settings("SavedAuth") = Token
My.Settings.Save()
End Sub
End Class

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