How to set VB Application Proxy Settings to Default System Proxy Settings - vb.net

My application is supposed to work on a Company Network where proxy is enabled,
By default when logged in all applications like browser and all can access internet normally
But when i open my application "The remote server returned an error [407] Proxy Authentication Required" error is coming
In normal internet connected PC it works well
Is there any way to set manual proxy or more preferably set the system proxy as default to the application
I am too novice in the programming field
My code is
Dim PartURL As String = "http://www.google.com"
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(PartURL)
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim sourcecode As String = sr.ReadToEnd()
SearchPageSource = sourcecode
Also my proxy settings is
Address: abcserver04
Port: 8080
Ipconfig output on cmd prompt is
Ethernet adapter local area connection
Connection Specific DNS Suffix : abc.defgroup.net
IP Address : 10.4.8.xx
Subnet Mask : 255.255.255.0
Default Gateway : 10.4.8.254

Try this...
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials

You can also use app.config.
From https://stackoverflow.com/a/8180854/239408
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>

Related

HTTPS webservice using WCF

I try to connect to https web service over proxy at my end.
below is code snippet
Dim strProxyURL As String = "http://myproxy.com"
Dim mypingRequest As New pingRequest()
Dim httpUri As New Uri("https://mysite.com")
Dim mybinding As New WSHttpBinding()
Dim remoteAddress As New EndpointAddress(httpUri)
mybinding.UseDefaultWebProxy = True
mybinding.BypassProxyOnLocal = True
mybinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Windows
mybinding.MessageEncoding = WSMessageEncoding.Mtom
mybinding.TextEncoding = System.Text.Encoding.UTF8
mybinding.Security.Mode = SecurityMode.TransportWithMessageCredential 'TransportWithMessageCredential
mybinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows
Dim myMBClient As New v1_PortTypeClient(mybinding, remoteAddress)
myMBClient.ClientCredentials.Windows.ClientCredential.UserName = "username"
myMBClient.ClientCredentials.Windows.ClientCredential.Password = "pwd"
myMBClient.ping()
when I use proxy I error proxy authentication required error
if I remove proxy from desktop and use direct internet then I go to site web service but cannot login even thought the gave correct username and password
issue is resolved. WCF web services uses Custom binding hence error. also i have add webrequest.defaultwebproxy and credentials to access via web proxy at requesting client side WCF Custom Http Proxy Authentication

WCF TCP Binding in a self hosted WinForms App

I have decided to do net.tcp binding in my self hosted wcf app (with transport level encryption).
While I had quite an interesting time in getting info on the subject of making a self hosted wcf app work, my current working solution does not implicitly specify binding, so I guess it defaults to BasicHttp.
I am unsure of how to "add/change" the binding to net.tcp and transport level encryption ? I am also curious in "testing" my tcp secured connection. What would be used to run some test security scenarios?
Working Code: No implicit binding specified...
'create URI
Dim myServiceAddress As New Uri("http://" & LocalIpAddress & ":" & tcp_port & "/" & servicename)
Dim myservicehost As New ServiceHost(GetType(plutocomm), myServiceAddress)
' Enable metadata publishing.
Dim smb As New ServiceMetadataBehavior()
smb.HttpGetEnabled = True
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
myservicehost.Description.Behaviors.Add(smb)
myservicehost.Open()
UPDATE
An Update on this... really starting to scratch my head here..
I have now:
Changed binding to tcp
Created, installed and referenced self signed certificate
trace shows no helpfull information...
Here's my new code:
Dim myServiceAddress As New Uri("net.tcp://" & localIpAddress & ":" & tcp_port & "/" & servicename)
Dim myservicehost As New ServiceHost(GetType(plutocomm))
'create binding
Dim myNetTcpBinding = New NetTcpBinding()
myNetTcpBinding.Security.Mode = SecurityMode.Transport
myNetTcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None
' Enable metadata publishing.
Dim smb As New ServiceMetadataBehavior()
smb.HttpGetEnabled = False
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
myservicehost.Description.Behaviors.Add(smb)
myservicehost.AddServiceEndpoint(GetType(Iplutocomm), myNetTcpBinding, myServiceAddress)
myservicehost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "louisvantonder")
myservicehost.Open()
Heres my trace with a "warning" when trying to reference it, no real info on why...?
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"><System xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"><EventID>262171</EventID><Type>3</Type><SubType Name="Warning">0</SubType><Level>4</Level><TimeCreated SystemTime="2013-05-28T01:16:53.0868677Z" /><Source Name="System.ServiceModel" /><Correlation ActivityID="{a696dcda-b24a-4838-9f23-cd0d67690af7}" /><Execution ProcessName="pluto" ProcessID="8472" ThreadID="3" /><Channel /><Computer>LOUISVANTONDER</Computer></System><ApplicationData><TraceData><DataItem><TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Warning"><TraceIdentifier>http://msdn.microsoft.com/en-ZA/library/System.ServiceModel.Channels.SocketConnectionAbort.aspx</TraceIdentifier><Description>SocketConnection aborted</Description><AppDomain>pluto.exe</AppDomain><Source>System.ServiceModel.Channels.SocketConnection/37489757</Source></TraceRecord></DataItem></TraceData></ApplicationData></E2ETraceEvent>
I still cant get a workable solution... here is my current code
You didn't specify a binding in your original code and you specified a protocol of http (via your address), which is why you're getting BasicHttpBinding (which is the default for http).
The following code snippet should get you going in the right direction:
Dim myServiceAddress As New Uri("net.tcp://" & LocalIpAddress & ":" & tcp_port & "/" & servicename)
Dim myservicehost As New ServiceHost(GetType(plutocomm), myServiceAddress)
Note the net.tcp protocol in the address. In theory, that should be sufficient to get you the default NetTCPBinding. If you want to explicitly define it, here's one way:
Create a NetTCP endpoint and add it to your ServiceHost:
Dim myservicehost As New ServiceHost(GetType(plutocomm))
Note that you're not creating the endpoint yet. The following code will create the endpoint for your sevice:
Dim myNetTcpBinding = New NetTcpBinding()
myNetTcpBinding.Security.Mode = SecurityMode.Transport
myNetTcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate
myservicehost.AddServiceEndpoint(typeof(plutocomm), myNetTcpBinding, myServiceAddress)
Note that SecurityMode.Transport is the default for NetTcpBinding, so you don't need to explicitly set it. If you're using certificate you'll probably need to tell the binding where to find the certificate (take a look at the MSDN Example).
This is just one of several ways you can set up the binding (you can also do it in the config file, for example).
The key here is that WCF (with version 4 and later) has default settings that will come into play unless you explicitly specify something else.

IIS Application Initialization module sending request to localhost

I have a WCF Service using MSMQ, hosted in IIS. The service doesn't fire up and read messages from the queue until the URL to the service's SVC page has been hit in a browser, which is problem after deployment and the app pool recycling. To resolve this I installed the IIS Application Initialization module which will send a fake request to a page specified in the Web.config like this:
<system.webServer>
<applicationInitialization remapManagedRequestsTo="Startup.htm" skipManagedModules="true" >
<add initializationPage="/MyService.svc" />
</applicationInitialization>
</system.webServer>
The problem I'm having is that it's hitting localhost when my site is bound to another domain, so I'm seeing this error:
WebHost failed to process a request. Sender Information:
System.ServiceModel.Activation.HostedHttpRequestAsyncResult/42715336
Exception: System.ServiceModel.ServiceActivationException: No protocol
binding matches the given address 'http://localhost/MyService.svc'.
Protocol bindings are configured at the Site level in IIS or WAS
configuration. ---> System.InvalidOperationException: No protocol
binding matches the given address 'http://localhost/MyService.svc'.
Protocol bindings are configured at the Site level in IIS or WAS
configuration.
Any ideas how I can resolve this?
I've done this with an SVN Service Connecting to an EMS Server so it should work. If it doesn't create an ASPX page that does something like the followign that can even exercise your service.
<%# Page aspcompat=true Language="VBScript" %>
Dim objSvrHTTP
Dim PostData
Dim WebName
Dim SoapAction
SoapAction = "Your Soap Action"
WebName = Request.URL.Host & ":" & Request.URL.Port
objSvrHTTP = Server.CreateObject("Msxml2.ServerXMLHTTP")
PostData = "Soap Post XML (Recoreded probably)"
objSvrHTTP.open("POST", "http://" & WebName & "/path/SVCFile.svc", false)
objSvrHTTP.setRequestHeader("Content-Type", "text/xml" )
' set SOAPAction as appropriate for the operation '
objSvrHTTP.setRequestHeader("SOAPAction", SoapAction )
objSvrHTTP.Send(cstr(PostData))
dim serviceResponse
dim ExpectedResponse
ExpectedResponse = "asdf"
serviceResponse = objSvrHTTP.responseText
if (serviceResponse <> ExpectedResponse) then
Response.Write("The Service Didn't return false and should have. it returned: " )
Response.Write(serviceResponse)
else
Response.Write("OK")
end if

Calling SharePoint Web Service over SSL in VB.Net (401 Unauthorized)

I'm trying to call the AddAttachment of the Lists.asmx SharePoint web service the below code works fine if I'm calling the web service over HTTP.
Dim img(MyFile.PostedFile.ContentLength - 1) As Byte
MyFile.PostedFile.InputStream.Read(img, 0, img.Length)
'Dim fStream As FileStream = File.OpenRead(FullFileName)
Dim fileName As String = MyFile.PostedFile.FileName.Substring(3)
Dim listService As New wsList.Lists()
Dim credentials As New System.Net.NetworkCredential(UserName, Password, Domain)
If Not SiteUrl.EndsWith("/") Then
SiteUrl += "/"
End If
SiteUrl += "_vti_bin/Lists.asmx"
'SiteUrl = SiteUrl.ToLower.Replace("http:", "https:")
listService.Url = SiteUrl
listService.Credentials = credentials
Dim addAttach As String = listService.AddAttachment(ListName, ItemId, fileName, img)
ReturnValue = True
However if I uncomment out this line
'SiteUrl = SiteUrl.ToLower.Replace("http:", "https:")
I will get the following error: The request failed with HTTP status 401: Unauthorized
Now if I leave the above line commented out AND then also comment out this line
listService.Credentials = credentials
I will get the same 401 error (expected) so it appears the credentials are being accepted correctly over HTTP but not HTTPS. Can one help explain this to me and have any thoughts on how to fix the issue?
Thanks in advance!
This morning I was working with one of our system guys. He checked some IIS logs and could see errors trying to access the web service over HTTPS. He went into Central Admin and added some Alternate Access Mappings to include the HTTPS urls. Then everything worked!

Accessing HTTPS site through Proxy Server

I am adding code to use a proxy server to access the Internet.
The code works fine when requesting a file from a normal (HTTP) location, but does not work when accessing a secure location (HTTPS).
This is the code that works just fine:
URL = "http://UnSecureSite.net/file.xml"
Dim wr As HttpWebRequest = CType(WebRequest.Create(URL), HttpWebRequest)
Dim proxy As System.Net.IWebProxy
proxy = WebRequest.GetSystemWebProxy
wr.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim ws As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
// (more work here)
As soon as I change the URL to go to HTTPS, I get a 407 returned to me.
Anyone have any ideas?
URL = "https://SecureSite.net/file.xml"
Dim wr As HttpWebRequest = CType(WebRequest.Create(URL), HttpWebRequest)
Dim proxy As System.Net.IWebProxy
proxy = WebRequest.GetSystemWebProxy
wr.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim myCache As New CredentialCache()
myCache.Add(New Uri("https://SecureSite.net"), "Basic", New NetworkCredential(UserName, Password))
wr.Credentials = myCache
Dim ws As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
// (more work here)
A HTTPS request through a web-proxy is different from a standard HTTP request. A regular HTTP request will use the GET method. However, a HTTPS request needs to use a CONNECT method. Then, the proxy will merely establish a tunnel to the server. Subsequent messages will be sent directly between the client and the server through the proxy tunnel. The proxy has no way of interpreting the data flowing in between.
Under normal situations:
Client -+- [CONNECT] ---> Proxy --- [DIRECT TCP] -+-> Server
| | |
+-------------[ENCRYPTED TCP]-------------+
I am not familiar enough with the VB code to know if that is what is happening. However, I suspect that it is not. The easiest way to check is to intercept the message being sent to the proxy. Make sure that it begins with a "CONNECT ...".