Are variables inside VB.NET shared function local only? - asp.net

ASP.NET VB.NET 3.5.
In the following function, called from a webpage AJAX, will the cVSession2 object be shared with other users (I don't want it to be)?
<WebMethod()> _
Public Shared Function fGPSUpdateSessionValues(ByVal strLatitude As String, ByVal strLongitude As String) As String
Dim strReturn As String = ""
Dim cVSession2 As New cVSession
With cVSession2
.pVSessionGPSLatitudeLastPosition = strLatitude
.pVSessionGPSLongitudeLastPosition = strLongitude
.fUpdate()
End With
cVSession2 = Nothing
Return strReturn
End Function

It appears local variables such as cVSession2 will not be shared with other users as per:
Does a static method share its local variables & what happens during concurrent usage from different threads?

Related

Why Dev express ReportService Saves classes but loads byte array?

When creating a report designer if a ReportStorageWebExtension is created, it has 2 set data methods and 1 method to get data.
Public Overrides Function GetData(ByVal url As String) As Byte()
' Returns report layout data stored in a Report Storage using the specified URL.
' This method is called only for valid URLs after the IsValidUrl method is called.
Return MyBase.GetData(url)
End Function
Public Overrides Sub SetData(ByVal report As XtraReport, ByVal url As String)
' Stores the specified report to a Report Storage using the specified URL.
' This method is called only after the IsValidUrl and CanSetData methods are called.
MyBase.SetData(report, url)
End Sub
Public Overrides Function SetNewData(ByVal report As XtraReport, ByVal defaultUrl As String) As String
' Stores the specified report using a new URL.
' The IsValidUrl and CanSetData methods are never called before this method.
' You can validate and correct the specified URL directly in the SetNewData method implementation
' and return the resulting URL used to save a report in your storage.
Return MyBase.SetNewData(report, defaultUrl)
End Function
Why does set data get a XtraReport but getting the data as byte()
As explained by Devexpress team in this ticket it is done like that so you can access to the report properties before you save it. and the proper way to save them is as a byte array like this(shown here):
Public Overrides Sub SetData(ByVal report As XtraReport, ByVal url As String)
' Write a report to the storage under the specified URL.
Dim row As DataRow = reportsTable.Rows.Find(Integer.Parse(url))
If row IsNot Nothing Then
Using ms As New MemoryStream()
report.SaveLayoutToXml(ms)
row("LayoutData") = ms.GetBuffer()
End Using
reportsTableAdapter.Update(catalogDataSet)
catalogDataSet.AcceptChanges()
End If
End Sub

Visual basic programmatically pass username and password to https url to make webbrowser display webpage and also download from webpage

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

How to change the serializer of WebMethod parameters

Ive discovered an issue in some of our old web code. The problem is that the default serializer isnt serializing the date properly. I want to use JSON.Net in order to serialize the parameters for the web methods in our aspx code. But im not sure how to tell it to use JSON.NET instead of using the default serializer.
Here is an example snipit of our code
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function EditApplication(ByVal Application As ApplicationModel, ByVal Country As String, ByVal Language As String) As jsonResponse
Dim r As New jsonResponse
Dim g As New ApplicationRequest
g.country = Country
g.locale = Language
g.platform = "Android"
g.timestamp = ""
g.transactionid = "abc123"
....
So I need ApplicationModel to serialize using JSON.Net. Thanks for your help.
Not sure if this will be helpful (since this is taken from the REST web service) but you can define it on OperationContract like this one below:
System.ServiceModel.Web.WebMessageFormat.Json
<OperationContract()> _
<WebGet(responseformat:=System.ServiceModel.Web.WebMessageFormat.Json)> _

Crystal Report convert to PDF (Error The logon to the database failed. ((0x8004100f)))

In my application I have some code to convert to PDF. In debug mode all is good and working but when I test it on then server I keep getting the logon to the database failed. I have no idea why I get the error becase the login and password are 100% ok.
tried 2 ways for the server of sending the report
SetCrystalReportFilePath(Server.MapPath("~/MemberPages/Report.rpt"))
SetPdfDestinationFilePath(Server.MapPath("~/MemberPages/Report_" & Report & ".pdf"))
SetRecordSelectionFormula("{Report.Report_id} =" & ID)
Transfer()
SetCrystalReportFilePath("C:\inetpub\wwwroot\Werkbon.rpt")
SetPdfDestinationFilePath("C:\inetpub\wwwroot\Werkbon_" & werkbonnr & ".pdf")
SetRecordSelectionFormula("{werkbon.werkbon_id} =" & werkbonnr)
Transfer()
Dim ConInfo As New CrystalDecisions.Shared.TableLogOnInfo
Dim oRDoc As New ReportDocument
Dim expo As New ExportOptions
Dim sRecSelFormula As String
Dim oDfDopt As New DiskFileDestinationOptions
Dim strCrystalReportFilePath As String
Dim strPdfFileDestinationPath As String
Public Function SetCrystalReportFilePath(ByVal CrystalReportFileNameFullPath As String)
strCrystalReportFilePath = CrystalReportFileNameFullPath
End Function
Public Function SetPdfDestinationFilePath(ByVal pdfFileNameFullPath As String)
strPdfFileDestinationPath = pdfFileNameFullPath
End Function
Public Function SetRecordSelectionFormula(ByVal recSelFormula As String)
sRecSelFormula = recSelFormula
End Function
Public Function Transfer()
oRDoc.Load(strCrystalReportFilePath)
oRDoc.RecordSelectionFormula = sRecSelFormula
oDfDopt.DiskFileName = strPdfFileDestinationPath
expo = oRDoc.ExportOptions
expo.ExportDestinationType = ExportDestinationType.DiskFile
expo.ExportFormatType = ExportFormatType.PortableDocFormat
expo.DestinationOptions = oDfDopt
oRDoc.SetDatabaseLogon("databasename", "password")
oRDoc.Export()
End Function
Crystal is very particular when swapping in and out connection information (especially with sub-reports if you have any). It's always been a sore spot that they haven't really made any better over the years. I have a blog entry I've shared that has extension methods I created (in VB.Net) to easily load and swap in new connections (typically I use ADO for the connection in the report). The extension methods can be found in this link (and below is an example of how to use them, ignore the System.Diagnostics line if you're using this from ASP.NET). Hope this helps.
http://www.blakepell.com/Blog/?p=487
Using rd As New ReportDocument
rd.Load("C:\Temp\CrystalReports\InternalAccountReport.rpt")
rd.ApplyNewServer("serverName or DSN", "databaseUsername", "databasePassword")
rd.ApplyParameters("AccountNumber=038PQRX922;", True)
rd.ExportToDisk(ExportFormatType.PortableDocFormat, "c:\temp\test.pdf")
rd.Close()
End Using
System.Diagnostics.Process.Start("c:\temp\test.pdf")

vb.net Web Server linq to sql returns

My last question was not clear. Im trying to make a web service in VB.net is their a way that i can return the results that i get from LINQ. ie "return objreturnLINQResults"
I have tryed to set my Public Function GetAlarmsByGUIS(ByVal DeptGUID As String, ByVal IdNumber As String) As Linq.DataContext . i just keep getting errors. help please.
Public Function GetAlarmsByGUIS(ByVal DeptGUID As String, ByVal IdNumber As String) As Linq.DataContext
Dim lqAlarms As New linqAlarmDumpDataContext
Dim Temp As String = ""
Dim n As Integer = 0
Dim GetAlrms = From r In lqAlarms.AlarmDrops _
Where r.DeptGUID = DeptGUID And Not r.AlarmsHandled.Contains(IdNumber) _
Order By r.TimeDate Descending _
Select r
Return GetAlrms
End Function
1) You can't create web service's method which returns DataContext object.Return values and input parameters of Web service methods must be serializable through the XmlSerializer class. DataContext is not serializable
2) The simplest way to avoid errors it is return an array of serializable objects. Like this Return GetAlrms.ToArray();

Resources