I'm using .NET Framework 4.0.
I have a function that creates and calls a Task. In some part of its process I need a value stored in the Session, but it returns Nothing because the Task doesn't have the HttpContext.
Here's an example:
Public Class Example
Inherits System.Web.Mvc.Controller
<AcceptVerbs("GET", "POST")>
Public Sub DoSomething()
Dim products As List(Of Product)
Dim something As New Task(Sub()
For Each product In products
product.Name = product.Name.ToUpper
product.Save()
Next
End Sub)
something.Start()
End Sub
End Class
Public Class Product
Public Sub OnProductSave()
Dim session = Web.HttpContext.Current.Session
Dim log As New Log()
log.UserId = session("UserId")
log.Date = DateTime.Now()
log.Save()
End Function
End Class
There is a way that I could use the HttpContext in the Task?
Obs.: In the example I could pass the value of UserId to the function, but in the real case it's more complex than that.
Obs.2: I know that I could create a variable with the value of HttpContext and after set it to the Task's HttpContext, but I think there could be a better way. :)
With normal HTTP I can download upload and navigate to routers but I can't find any code to do any of that when the routers are on HTTPS.
To download I use this:
Try
My.Computer.Network.DownloadFile("http://" & "180.29.74.70" & "/cgi-bin/log.cgi", "C:\Users\ssb\Desktop\randomword.txt", "username", "password")
WebBrowser1.Refresh()
Catch ex As Exception
MessageBox.Show("Router not sufficient for operation Return for Inspection cannot download log file")
End Try
To upload a file I use this:
My.Computer.Network.UploadFile("C:\Users\ssb\Desktop\tomtn.txt", "http://" & "180.29.74.70" & "/cgi-bin/updateconfig.cgi", "username", "password")
To navigate to a web page on HTTP I use this:
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
But when I use HTTPS:
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
I get this security alert:
Then I click on yes and it goes to the pageābut I need the code to bypass any security questions like these.
Even though they're loosely related, you've presented two separate questions here.
Why is the call failing when I use the WebBrowser control to load a page via HTTPS?
Why is the call failing when I use the DownloadFile() method to download a file via HTTPS?
First, you need to eliminate the possibility that your code is failing. Try both of the tasks above using public HTTPS URLs that are known to work correctly.
If you discover that the source of the problem is your private URL, you may want to consider whether you want to ignore SSL errors in your WebBrowser control.
You can do so using the (untested, translated to VB) code from this blog post:
Partial Public Class Form1
Inherits Form
Private WithEvents WebBrowser As New WebBrowser
Private Sub WebBrowser_DocumentCompleted(Sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser.DocumentCompleted
If e.Url.ToString() = "about:blank" Then
'create a certificate mismatch
WebBrowser.Navigate("https://74.125.225.229/")
End If
End Sub
End Class
<Guid("6D5140C1-7436-11CE-8034-00AA006009FA")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
<ComImport>
Public Interface UCOMIServiceProvider
<PreserveSig>
Function QueryService(<[In]> ByRef guidService As Guid, <[In]> ByRef riid As Guid, <Out> ByRef ppvObject As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
End Interface
<ComImport>
<ComVisible(True)>
<Guid("79eac9d5-bafa-11ce-8c82-00aa004ba90b")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IWindowForBindingUI
<PreserveSig>
Function GetWindow(<[In]> ByRef rguidReason As Guid, <[In], Out> ByRef phwnd As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
End Interface
<ComImport>
<ComVisible(True)>
<Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IHttpSecurity
'derived from IWindowForBindingUI
<PreserveSig>
Function GetWindow(<[In]> ByRef rguidReason As Guid, <[In], Out> ByRef phwnd As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
<PreserveSig>
Function OnSecurityProblem(<[In], MarshalAs(UnmanagedType.U4)> dwProblem As UInteger) As Integer
End Interface
Public Class MyWebBrowser
Inherits WebBrowser
Public Shared IID_IHttpSecurity As New Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b")
Public Shared IID_IWindowForBindingUI As New Guid("79eac9d5-bafa-11ce-8c82-00aa004ba90b")
Public Const S_OK As Integer = 0
Public Const S_FALSE As Integer = 1
Public Const E_NOINTERFACE As Integer = &H80004002
Public Const RPC_E_RETRY As Integer = &H80010109
Protected Overrides Function CreateWebBrowserSiteBase() As WebBrowserSiteBase
Return New MyWebBrowserSite(Me)
End Function
Private Class MyWebBrowserSite
Inherits WebBrowserSite
Implements UCOMIServiceProvider
Implements IHttpSecurity
Implements IWindowForBindingUI
Private myWebBrowser As MyWebBrowser
Public Sub New(myWebBrowser As MyWebBrowser)
MyBase.New(myWebBrowser)
Me.myWebBrowser = myWebBrowser
End Sub
Public Function QueryService(ByRef guidService As Guid, ByRef riid As Guid, ByRef ppvObject As IntPtr) As Integer Implements UCOMIServiceProvider.QueryService
If riid = IID_IHttpSecurity Then
ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IHttpSecurity))
Return S_OK
End If
If riid = IID_IWindowForBindingUI Then
ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IWindowForBindingUI))
Return S_OK
End If
ppvObject = IntPtr.Zero
Return E_NOINTERFACE
End Function
Public Function GetWindow(ByRef rguidReason As Guid, ByRef phwnd As IntPtr) As Integer Implements IHttpSecurity.GetWindow, IWindowForBindingUI.GetWindow
If rguidReason = IID_IHttpSecurity OrElse rguidReason = IID_IWindowForBindingUI Then
phwnd = myWebBrowser.Handle
Return S_OK
Else
phwnd = IntPtr.Zero
Return S_FALSE
End If
End Function
Public Function OnSecurityProblem(dwProblem As UInteger) As Integer Implements IHttpSecurity.OnSecurityProblem
'ignore errors
'undocumented return code, does not work on IE6
Return S_OK
End Function
End Class
End Class
Regarding problem #2: It appears you may be confusing WebBrowser and DownloadFile(). As you've probably already discovered, the WebBrowser control doesn't download files. However, you can simulate the behavior using this technique:
Partial Public Class Form2
Inherits Form
Private Sub WebBrowser_Navigating(Sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser.Navigating
Dim sFilePath As String
Dim oClient As Net.WebClient
' This can be any conditional criteria you wish '
If (e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".pdf")) Then
SaveFileDialog.FileName = e.Url.Segments(e.Url.Segments.Length - 1)
e.Cancel = True
If SaveFileDialog.ShowDialog() = DialogResult.OK Then
sFilePath = SaveFileDialog.FileName
oClient = New Net.WebClient
AddHandler oClient.DownloadFileCompleted, New AsyncCompletedEventHandler(AddressOf DownloadFileCompleted)
oClient.DownloadFileAsync(e.Url, sFilePath)
End If
End If
End Sub
Private Sub DownloadFileCompleted(Sender As Object, e As AsyncCompletedEventArgs)
MessageBox.Show("File downloaded")
End Sub
Private WithEvents SaveFileDialog As New SaveFileDialog
Private WithEvents WebBrowser As New WebBrowser
End Class
In any event, the first step in solving this is to figure out whether it's your code or the private URL that's causing your issue.
The main thing needed here is to programatically download a file from a https url while using a username and password blocked by the security certificate issue
and the solution after searching for 2 weeks is
To Download a file you can disable the security cerificate request temporaraly with the following code then after the code ran it enables the security certicate again
First code you dont even need a browser it automatically saves the file to you desktop
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'check if a simular file doesnt exists so you can create a new file and deletes the file if it exists
If File.Exists("C:\pathtoyourfile\yourfilename.txt") Then
File.Delete("C:\pathtoyourfile\yourfilename.txt")
End If
'Type this before your download or hhtps request
'ByPass SSL Certificate Validation Checking
System.Net.ServicePointManager.ServerCertificateValidationCallback =
Function(se As Object,
cert As System.Security.Cryptography.X509Certificates.X509Certificate,
chain As System.Security.Cryptography.X509Certificates.X509Chain,
sslerror As System.Net.Security.SslPolicyErrors) True
'Call web application/web service with HTTPS URL here
'=========================================================================================
'ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
Try
My.Computer.Network.DownloadFile("https://176.53.78.22/filenameonserveryouwanttodownload", "C:\pathtoyourfile\yourfilename.txt", "Yourusername", "yourpassword")
WebBrowser1.Refresh()
Catch ex As Exception
MessageBox.Show("message saying something didnt work")
'exit sub if it worked
Exit Sub
End Try
MessageBox.Show(" message saying it worked")
'=========================================================================================
'Restore SSL Certificate Validation Checking
System.Net.ServicePointManager.ServerCertificateValidationCallback = Nothing
End Sub
then to browse to a webaddress the following code will popup and the security popup will popup but just select yes browsing on the webpage works normally
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
As you said:
[...] I need the code to bypass any security questions like these.
In other word, you need to "automatically accept self signed SSL certificate", so in my opinion it is a duplicate question with : VB .net Accept Self-Signed SSL certificate, which may fit your needs.
and most especially slaks answer:
In VB.Net, you need to write:
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
I'm trying to set up some WCF services that are connected and pass a custom HTTP header from service to service.
That is my client call ServiceX, which calls ServiceY, which writes to the DB.
They are originally called from a Silverlight 5 client in some cases, other cases from an ASP.NET web app.
I implemented IClientMessageInspector and IDispatchMessageInspector to pass the header from service to service, and in the DispatchMessageInspector I wrote the header to an implementation of IExtension(Of OperationContext) (see below).
However, I wanted this data only to exist for the duration of the call, but it seems to be sticking around in the services under certain circumstances as I keep seeing the same header data repeated in different calls.
Ultimately, I want to be able to pass a custom header to a WCF service, persist it only while that call exists, send it to the next service in the header, and wipe out that service instance. Am I wrong in my thinking that using a PerCall WCF service setup and OperationContext is the right way to do that?
Here is my implementation of IExtension(Of OperationContext). The auditTransactionId is the thing I want to pass in the service. As well, the Current() property is where I keep seeing existing data:
Imports System.ServiceModel
Public Class CustomOperationContextExtension
Implements IExtension(Of OperationContext)
Private ReadOnly m_items As IDictionary(Of String, Object)
Private m_auditTransactionId As String
Private Sub New()
m_items = New Dictionary(Of String, Object)()
End Sub
Public ReadOnly Property Items() As IDictionary(Of String, Object)
Get
Return m_items
End Get
End Property
Public Property AuditTransactionId() As String
Get
Return m_auditTransactionId
End Get
Set(value As String)
m_auditTransactionId = value
End Set
End Property
Public Shared ReadOnly Property Current() As CustomOperationContextExtension
Get
If (OperationContext.Current IsNot Nothing) Then
Dim context As CustomOperationContextExtension = OperationContext.Current.Extensions.Find(Of CustomOperationContextExtension)()
If context Is Nothing Then
context = New CustomOperationContextExtension()
OperationContext.Current.Extensions.Add(context)
End If
Return context
End If
Return Nothing
End Get
End Property
Public Sub Attach(owner As OperationContext) Implements IExtension(Of System.ServiceModel.OperationContext).Attach
End Sub
Public Sub Detach(owner As OperationContext) Implements IExtension(Of System.ServiceModel.OperationContext).Detach
End Sub
End Class
EDIT:
When I say that data is sticking around, I mean that when I call Current in a new service call I expect the Extensions list to be empty (in the code below in the Current() property), but there is always an existing instance of CustomOperationContextExtension there already that is left over fro a previous call. I'm not sure under which circumstances this happens.
I have implement a Public shared function in my aspx.vb page (not in class or web service) to use it with javascript but I had problem with creating a cookies and sessions
How can I create cookies or sessions in that shared function? any ideia!
Thank you all.
<WebMethod> _ Public Shared Sub Test(text As String)
Dim ctx As HttpContext = System.Web.HttpContext.Current
ctx.Session("Test") = text
ctx.Response.Cookies("TestCookie").Value = text
End Sub
I've the following class which is a singleton implementation:
Imports Microsoft.VisualBasic
Imports System.Xml
Public Class GlobalController
Private Shared instance As GlobalController
Private ControlsXmlDoc As XmlDocument
Private xmldocpath As String
Sub New()
ControlsXmlDoc = New XmlDocument
xmldocpath = HttpContext.Current.Server.MapPath("~/cp/GlobalControl.xml")
ControlsXmlDoc.Load(xmldocpath)
End Sub
Shared Function GetInstance() As GlobalController
If instance Is Nothing Then
Return New GlobalController
Else
Return instance
End If
End Function
Shared Property IsExtracting() As Boolean
Get
Return Boolean.Parse(GetInstance.ControlsXmlDoc.SelectNodes("global/extraction/proceed").Item(0).InnerText)
End Get
Set(ByVal value As Boolean)
HttpContext.Current.Application.Lock()
Dim node As XmlNode = GetInstance.ControlsXmlDoc.SelectNodes("global/extraction/proceed").Item(0)
If Not Boolean.Parse(node.InnerText) = value Then
node.InnerText = value.ToString
node.Normalize()
SaveDocument()
GetInstance.ControlsXmlDoc.Load(GetInstance.xmldocpath)
End If
HttpContext.Current.Application.UnLock()
End Set
End Property
Shared Sub SaveDocument()
GetInstance.ControlsXmlDoc.Save(GetInstance.xmldocpath)
End Sub
End Class
In my page I am doing something like this:
GlobalController.IsExtracting = False
Response.Write(GlobalController.IsExtracting)
I am always getting the output as "true". What is wrong with the code?
According this link Operator precedence and associativity, ! (or vb.net Not) have greater priority than == (= in VB.NET); so, your expression is always evaluated as
Not(True) And False
and never enters that If statement.
Try to use Boolean.Parse(node.InnerText) != value or Not (Boolean.Parse(node.InnerText) = value) in order to get correct result.
All, thanx for ur answers. I apologize for what I am about to say. I found the bug: it was with the way I implemented the singleton. Forgot to assign the newly created object instance to the shared variable.
Shared Function GetInstance() As GlobalController
If instance Is Nothing Then
instance = New GlobalController
End If
Return instance
End Function