I'm writing an ASP.NET (VS2013) web app that uses LINQ to SQL. The datacontext is created via the graphical interface and it works great. I need to switch from DEV to INT and then to PROD programmatically.
sounds simple and after reading many, many postings I'm super frustrated.
When I switch to DEV it works because the connection already exists. when I switch to INT it fails but NOT because the authentication but because the the Store Procedure doesn't exist... that makes NO sense...
can anyone please help me with tested statements??? (i already tried lots of "I think...")
----WP_LINQ2SQLDB.DESIGNER.VB----
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Data.Linq
Imports System.Data.Linq.Mapping
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Reflection
<Global.System.Data.Linq.Mapping.DatabaseAttribute(Name:="WorkOrder")> _
Partial Public NotInheritable Class WP_LinQ2SQLDataContext
Inherits System.Data.Linq.DataContext
Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource()
#Region "Extensibility Method Definitions"
Partial Private Sub OnCreated()
End Sub
#End Region
Public Sub New()
MyBase.New("", mappingSource)
OnCreated()
End Sub
Public Sub New(ByVal connection As String)
MyBase.New(connection, mappingSource)
OnCreated()
End Sub
etc...
----WP_LINQ2SQLDB.VB----
Inherits System.Data.Linq.DataContext
Private Sub OnCreated()
Dim connectionStr As String = Nothing
Select Case My.Settings.DB_to_Use
Case "DEV"
Case "INT"
connectionStr = "Data Source=SERVER\DBINST;Initial Catalog=CAT_Order;Integrated Security=True;"
Case "PRD"
End Select
Dim DB_TUAcct = My.Settings.DB_TUAcct
Dim DB_TUPwd = My.Settings.DB_TUPwd
connectionStr = connectionStr + "User ID=Domain\blah" + DB_TUAcct.ToUpper + ";Password=" + My.Settings.DB_TUPwd + ";"
----DEFAULT.VB----
' I've tried...
Dim dc As WP_LinQ2SQLDataContext = New WP_LinQ2SQLDataContext(temp)
Dim dc As WP_LinQ2SQLDataContext = New WP_LinQ2SQLDataContext(builder.ConnectionString)
' building a connection string from sql builder
Dim builder2 As IDbConnection = New SqlClient.SqlConnection(temp)
dc.Connection.ConnectionString = builder.ConnectionString
BUT at the end of the day, I cannot make the LINQ to fail because the connection string is bad... and I dont know to fix...
Related
I'm working on a Asp.Net project where I'm trying to add "Hangfire" library for background jobs.
I've installed all required packages according doccumentation and also created the test database.
I've also added the required startup methods in Global.asax.vb (had to convert from c#, given in the example, to vb.net) so my file looks like this:
Imports Hangfire
Imports Hangfire.SqlServer
Public Class Global_asax
Inherits HttpApplication
Sub Application_Start(sender As Object, e As EventArgs)
' Fires when the application is started
Try
HangfireAspNet.Use(GetHangfireServers)
Catch ex As Exception
Debug.Assert(False, "Not Yet Ready")
End Try
End Sub
Private Iterator Function GetHangfireServers() As IEnumerable(Of IDisposable)
GlobalConfiguration.Configuration.SetDataCompatibilityLevel(CompatibilityLevel.Version_170).UseSimpleAssemblyNameTypeSerializer().UseRecommendedSerializerSettings().UseSqlServerStorage("Data Source=xxx,00000;Initial Catalog=xxx;User ID=xxx;Password=xxx", New SqlServerStorageOptions With {
.CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
.SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
.QueuePollInterval = TimeSpan.Zero,
.UseRecommendedIsolationLevel = True,
.DisableGlobalLocks = True
})
Yield New BackgroundJobServer()
End Function
End Class
And the
HangfireAspNet.Use(GetHangfireServers)
line is throwing the next exception:
Unable to cast object of type 'VB$StateMachine_6_GetHangfireServers' to type 'System.Func1[System.Collections.Generic.IEnumerable1[System.IDisposable]]
I've verified that the connection string is OK and it connects to the test database with no problems, but I'm stuck regarding the exception.
Any help?
This is how I solved my problem, just putting the function inside the Use():
Public Shared Sub Init()
Dim connStr = "Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx"
HangfireAspNet.Use(
Iterator Function()
GlobalConfiguration.Configuration.SetDataCompatibilityLevel(CompatibilityLevel.Version_170).UseSimpleAssemblyNameTypeSerializer().UseRecommendedSerializerSettings().UseSqlServerStorage(connStr, New SqlServerStorageOptions With {
.CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
.SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
.QueuePollInterval = TimeSpan.Zero,
.UseRecommendedIsolationLevel = True,
.DisableGlobalLocks = True
})
Yield New BackgroundJobServer()
End Function
)
End Sub
In VB you have to use AddressOf in your proc call, i.e.:
HangfireAspNet.Use(AddressOf GetHangfireServers)
Firstly, I apologize if i have raised this incorrectly or not quite to the rules. It is my first post.
Can someone please help with my issue.
I have an web application that is fully functioning and authorizes the user.
my problem is that i want to add a check when the site loads to see if the PC is currently connected to the work network. EG. when at home and not connected via VPN I want to redirect to an error page stating not connected to the AD Domain Network.
Currently the app just crashes with exception of "ldap server cannot be reached".
I hope this makes sense.
CODE ADDED
Imports Microsoft.VisualBasic
Imports System.Security.Principal
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.Configuration.ConfigurationManager
Public Class Gen
Dim DomUser As System.DirectoryServices.AccountManagement.UserPrincipal = System.DirectoryServices.AccountManagement.UserPrincipal.Current
Public ADUser As String = AppSettings("DomainPrefix").ToString & DomUser.SamAccountName
Public ADEmail As String = DomUser.EmailAddress
Public ADForname As String = DomUser.GivenName
Public ADSurname As String = DomUser.Surname
Public ADFullName As String = ADForname & " " & ADSurname
Public wi As WindowsIdentity = HttpContext.Current.User.Identity
End Class
Culprit line is
Dim DomUser As System.DirectoryServices.AccountManagement.UserPrincipal = System.DirectoryServices.AccountManagement.UserPrincipal.Current
The best approach is to use the proper OOP paradigm.
Public Function CheckLDAP() As Boolean
Dim DomUser As System.DirectoryServices.AccountManagement.UserPrincipal
Dim blnLDAPOk As Boolean = False
Try
DomUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
blnLDAPOk = True
Catch ex as Exception
' Perhaps Throw an exception to be handled
End Try
Return blnLDAPOk
End Function
From the class Gen, instantiate the class
Dim gLDAP = New Gen
If (gLDAP.CheckLDAP()) Then
' We are in
Else
' Whoops, no LDAP found
End If
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
Got a script to run crystal report over ASP.Net, export and send to email.
If I use the current database without applying logon everything works but if I change datasource (same database structure but different server) at runtime then the issue below.
Crystal 2008 runtime
ERROR:System.Runtime.InteropServices.COMException (0x80042018): The
table %1 does not exist in the document. at
CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.VerifyTableConnectivity(Object
Table) at
CrystalDecisions.CrystalReports.Engine.Table.TestConnectivity() at
ScriptCodeClass.ApplyLogon(ReportDocument cr, ConnectionInfo ci) at
ScriptCodeClass.Logon(ReportDocument cr, String server, String db,
String id, String pass) at ScriptCodeClass.FunCreatePDFView(String
lsHeader, String lsReportType, String msDatabaseUserId, String
msDatabasePassword)
this code can change authentication but not data source/server, wondering if need a reference or to import.
Imports System.Collections
Imports System.Data
Imports T1.Tb.Data
Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports T1.Tb
Imports T1.TB.Public
Imports CrystalDecisions.CrystalReports.Engine.ReportDocument
Imports CrystalDecisions.ReportSource
Imports System.Configuration
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
References CrystalDecisions.CrystalReports.Engine
References CrystalDecisions.Shared
References System.Web.Services
References System.Data
References T1.Tb.dll
References T1.TB.Public
References T1.P1.dll
References T1.P1.Public
References T1.Tb.Fun
public shared function Logon(cr as ReportDocument, server as string, db as string, id as string, pass as string) as Boolean
'Use this to change the database logon info for a crystal report
dim ci as ConnectionInfo = new ConnectionInfo()
dim subObj as SubreportObject
ci.ServerName = server
ci.DatabaseName = db
ci.UserID = id
ci.Password = pass
if ApplyLogon(cr, ci) then
for each obj as ReportObject in cr.ReportDefinition.ReportObjects
If (obj.Kind = ReportObjectKind.SubreportObject) Then
// if typeof obj.Kind.GetType() is CrystalDecisions.Shared.ReportObjectKind then
subObj = ctype(obj, SubreportObject)
if not ApplyLogon(cr.OpenSubreport(subObj.SubreportName), ci) then
return(false)
end if
end if
next
Logon = True
end if
end function
private shared function ApplyLogon(cr as ReportDocument, ci as ConnectionInfo ) as Boolean
dim li as TableLogOnInfo
dim success as Boolean
for each tbl as Table in cr.Database.Tables
li = tbl.LogOnInfo
li.ConnectionInfo = ci
tbl.ApplyLogOnInfo(li)
'check if logon was successful
'if TestConnectivity returns false, check logon credentials
if tbl.TestConnectivity() then
'drop fully qualified table location
if tbl.Location.IndexOf(".") > 0 then
tbl.Location = tbl.Location.Substring(tbl.Location.LastIndexOf(".") + 1)
else
tbl.Location = tbl.Location 'THIS IS LINE LEFT OUT IN ALL SAMPLES I SAW
end if
else
success = false
exit for
end if
success = True
next
end function
try to build the query as string in code first then pass its results to crystal reports to have the report and send it by email.
steps:
1) build a query string.
2) execute that string and fill a datatable inside a dataset with the results
3) use that dataset / datatable to generate the report in crystal reports
You have several choices:
Add Key(s) in web.config as follow :
<add key="ServerName" value=""/> Name Or IP Address
<add key="DataBaseName" value=""/> Database Name
<add key="DatabaseUser" value=""/>User Name
<add key="DatabasePassword" value=""/>Password
and call these keys in your reportviewer on load or on your event as :
Dim SERVER_NAME As String = ConfigurationManager.AppSettings("ServerName").ToString()
Dim DATABASE_NAME As String = ConfigurationManager.AppSettings("DataBaseName").ToString()
Dim DatabaseUser As String = ConfigurationManager.AppSettings("DatabaseUser").ToString()
Dim DatabasePassword As String = ConfigurationManager.AppSettings("DatabasePassword").ToString()
add your code and login to DB
CrystalReportViewer.SetDatabaseLogon(DatabaseUser, DatabasePassword, SERVER_NAME, DATABASE_NAME)
then add your datasource:
CrystalReportViewer.SetDataSource
Or you can pass it directly through your viewer as follow:
CrystalReportViewer.SetDatabaseLogon("sa", "123", "Your_Server", "YourDB")
I am a new developer.
I have a problem of creating a website that needs to access one user account and retrieve all his information in that database through different webpages like one page for viewing his profile data; another page to view the exams that he already created ... etc.
What I did was for each single aspx page I had to create a new object and connect to the SQL Server database from that object which I feel there's something wrong with that.
The question is there any way that I can define the database object only once and make it accessible from different webpages in the same website and execute SQL queries from that object and retrieve data?
Thanks
We use this implementation using MVC...maybe you could adapt it to your needs:
clsConnectionManager
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Data.SqlClient
Imports System.Web.Configuration
Imports System.Data
Public Class clsConnectionManager
Implements IDisposable
<ThreadStatic> _
Private Shared pSqlConnection As SqlConnection
Private Shared pConnectionString As String
Public Shared ReadOnly Property Connection() As SqlConnection
Get
If pSqlConnection Is Nothing Then
pConnectionString = WebConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
pSqlConnection = New SqlConnection(pConnectionString)
pSqlConnection.Open()
End If
If pSqlConnection.State = ConnectionState.Closed Then
pSqlConnection.Open()
End If
Return pSqlConnection
End Get
End Property
Public Sub Dispose() Implements System.IDisposable.Dispose
If pSqlConnection IsNot Nothing Then
pSqlConnection.Close()
End If
End Sub
End Class
Web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=yourDBName;User ID=YourDBUserName;Password=YourUserPassword" providerName="System.Data.SqlClient" />
</connectionStrings>
Use
Inside your classes you could do something like this:
Public Sub dbGetAll()
Try
Using New clsConnectionManager()
Using lObjSQLCommand = New SqlClient.SqlCommand("StoredProcedureName", clsConnectionManager.Connection)
lObjSQLCommand.CommandType = CommandType.StoredProcedure
Using lObjSqlDataReader As SqlClient.SqlDataReader = lObjSQLCommand.ExecuteReader()
Do While lObjSqlDataReader.Read()
/*Read rows...*/
Loop
End Using
End Using
End Using
Catch ex As Exception
Throw ex
End Try
End Sub
You can define the connection settings in the web.config file and access the same in your.aspx page.
Refer http://www.connectionstrings.com/store-connection-string-in-webconfig/