Windows command to view all DSNs? - odbc

I have some VB code that connects to a DSN (data source) setup on this Windows machine. The code looks like:
Dim myConnection As OdbcConnection = New OdbcConnection()
myConnection.ConnectionString = "DSN=MYALERTS"
It still works & connects, however the user who set this up is no longer around. I need to view/edit this, but when I go into "ODBC Data Source Administrator" in Windows I see no DSNs listed. I assume this is because I'm under my own user. Even under "System DSN" tab, the list is blank.
Is there a Windows command (or even VB code) to view all DSNs on this Windows 7 machine?

I was able to view all DSNs in the registry:
HKEY_LOCAL_MACHINE->SOFTWARE->ODBC->ODBC.INI

I realize this is a little dated, but perhaps will help someone. When using the ODBC Manager on a 64 bit Windows OS, you will only see 64 ODBC connections. If the connection you are seeking was setup for 32 bit, you can browse down to \Windows\SysWOW64\odbcad32.exe applet and manage the legacy 32 bit DSNs. This is helpful when working with applications that are compiled to target 32 bit.

This prints user and system DSN (data source name) from Windows registry.
Module ModuleDsn
Public Enum DataSourceType
System
User
End Enum
Sub Main()
Dim SU As SortedList = GetDataSourceNames(DataSourceType.User)
Dim SS As SortedList = GetDataSourceNames(DataSourceType.System)
Dim count As Integer = SU.Count + SS.Count
Dim mKeys As [String]() = New String(count - 1) {}
SU.Keys.CopyTo(mKeys, 0)
SS.Keys.CopyTo(mKeys, SU.Keys.Count)
For i As Integer = 0 To mKeys.Length - 1
Console.WriteLine(mKeys(i))
Next
End Sub
Public Function GetDataSourceNames(ByVal dsnType As DataSourceType) As System.Collections.SortedList
Dim dsnList As New System.Collections.SortedList()
Dim reg As Microsoft.Win32.RegistryKey = Nothing
If dsnType = DataSourceType.User Then
reg = (Microsoft.Win32.Registry.CurrentUser).OpenSubKey("Software")
Else
reg = (Microsoft.Win32.Registry.LocalMachine).OpenSubKey("Software")
End If
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC.INI")
If reg IsNot Nothing Then
reg = reg.OpenSubKey("ODBC Data Sources")
If reg IsNot Nothing Then
For Each sName As String In reg.GetValueNames()
dsnList.Add(sName, DataSourceType.User)
Next
End If
Try
reg.Close()
Catch
End Try
End If
End If
End If
Return dsnList
End Function
End Module

Related

Can't share isolated storage file between applications in different app pools

I've got various web apps (containing WCF services) in IIS under the default website. As long as they are all running in the same app pool they can access a shared isolated storage file no problem.
However, once I move them to different app pools I get "System.IO.IsolatedStorage.IsolatedStorageException: Unable to create mutex" when one tries to access a file created by another. They are all running under NetworkService user. I tried GetUserStoreForAssembly and GetMachineStoreForAssembly all with the same result. Any ideas why they couldn't use a shared file?
I made sure to close the stream and even dispose it in case one was holding onto it, but I am running a simple test where one service writes it, then another tries to read from it later, and it always fails.
Also, I am accessing the isolated store from a signed assembly.
Does anybody have any ideas?
Here is the code:
Private Sub LoadData()
Dim filename = FullFilePath(_fileName)
Dim isoStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly()
' Tried GetMachineStoreForAssembly, same failure
isoStorage.CreateDirectory(ROOT_DIRECTORY)
If (isoStorage.GetFileNames(filename).Length = 0) Then
Return
End If
Dim stream As Stream = New IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, isoStorage)
If stream IsNot Nothing Then
Try
Dim formatter As IFormatter = New BinaryFormatter()
Dim appData As Hashtable = DirectCast(formatter.Deserialize(stream), Hashtable)
Dim enumerator As IDictionaryEnumerator = appData.GetEnumerator()
While enumerator.MoveNext()
Me(enumerator.Key) = enumerator.Value
End While
Finally
stream.Close()
stream.Dispose()
stream = Nothing
End Try
End If
End Sub
Public Sub Save()
Dim filename = FullFilePath(_fileName)
' Open the stream from the IsolatedStorage.
Dim isoFile As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly()
' Tried GetMachineStoreForAssembly, same failure
Dim stream As Stream = New IsolatedStorageFileStream(filename, FileMode.Create, isoFile)
If stream IsNot Nothing Then
Try
Dim formatter As IFormatter = New BinaryFormatter()
formatter.Serialize(stream, DirectCast(Me, Hashtable))
Finally
stream.Close()
stream.Dispose()
stream = Nothing
End Try
End If
End Sub
Looks like it was a trust issue.
After adding the assembly accessing the isolated storage file to the gac it magically worked as everything in the gac has full trust set automatically.
This works for me, but it might not always be an option to do this for other solutions. Check out the .NET Framework caspol utility if this is the case.
Hope this helps somebody! It was a huge pitafor me.

Enterprise Library 5.0 Connection Pool Timeout

I have an old web application written in ASP.Net 2.0 Web Forms. I use the Data Access Block in Enterprise Library and have recently updated to version 5.0. The application is tiered, ie, UI layer, Service Layer, Data Layer. It also uses SQL Server 2008 for the data storage.
I have recently noticed that the following error is appearing when I run the application and browse to particular pages.
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
This tends to happen on pages that do a lot of separate reads from the database, maybe up to as many as 20 on one page.
Below shows snippets of my Data Access Class.
Public Class DataAccess
' create a private instance of the database factory
Private db As Database = DatabaseFactory.CreateDatabase()
Public Function ExecuteNonQuery(ByVal params() As SqlParameter, ByVal strSproc As String) As Integer
Dim intReturnValue As Integer = 0
Dim i As Integer
Dim cmd As DbCommand
cmd = db.GetStoredProcCommand(strSproc)
cmd.CommandTimeout = 120
For i = 0 To params.Length - 1
db.AddInParameter(cmd, params(i).ParameterName.ToString, params(i).DbType, params(i).Value)
Next
db.AddParameter(cmd, "return_value", DbType.Int32, ParameterDirection.ReturnValue, "", DataRowVersion.Default, 0)
db.ExecuteNonQuery(cmd)
intReturnValue = Int32.Parse(db.GetParameterValue(cmd, "#return_value"))
Return intReturnValue
End Function
Public Function ExecuteDataReader(ByVal params() As SqlParameter, ByVal SProc As String) As SqlDataReader
Dim i As Integer
Dim dr As SqlDataReader = Nothing
Dim cmd As DbCommand
cmd = db.GetStoredProcCommand(SProc)
cmd.CommandTimeout = 120
For i = 0 To params.Length - 1
db.AddInParameter(cmd, params(i).ParameterName.ToString, params(i).DbType, params(i).Value)
Next
dr = TryCast(DirectCast(db.ExecuteReader(cmd), RefCountingDataReader).InnerReader, SqlDataReader)
Return dr
End Function
Throughout my code, once I have finished with an SqlDataReader I always do something like this
If Not (drSource Is Nothing) Then
drSource.Close()
End If
Is there anything you folk can see that I am missing? Does it look like my code could be leaking connections or not closing properly?
I always thought the Garbage collector got rid of any open connections.
Any feedback or help would be greatly appreciated.
Thanks.
Your code is closing the data reader, but not the data connection associated with it.
Since your data reader is a SqlDataReader, it has a Connection property. You should be able to use that to close and dispose of the connection.

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

Direct Printing in Asp.net

In my application,i need to print my reports without converting to pdf or any other formats.I need to print the record as soon as the user clicks the print button.i have used the following code.but unfortunately,this is not direct print,it is converting into pdf and then printing.converting to pdf takes a lot of time which makes our life dreadful.Below is my code.Please help....
Private Sub imgPrint_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgPrint.Click
'Function to open connection and table
Dim dt As DataTable
Dim SQLString As String = TKSUCSearchChild.SQLWhereClause
Try
'dt = GetTableData("View_Item", SQLString, SQLOrderByClause)
'dt = Your DataTable
oRpt = New YourReportName
oRpt.SetDataSource(dt)
View_PickingSlip.ReportSource = oRpt
Dim exp As ExportOptions
Dim req As ExportRequestContext
Dim st As System.IO.Stream
Dim b() As Byte
Dim pg As Page
pg = View_PickingSlip.Page
exp = New ExportOptions
exp.ExportFormatType = ExportFormatType.PortableDocFormat
exp.FormatOptions = New PdfRtfWordFormatOptions
req = New ExportRequestContext
req.ExportInfo = exp
With oRpt.FormatEngine.PrintOptions
.PaperSize = PaperSize.PaperLegal
.PaperOrientation = PaperOrientation.Landscape
End With
st = oRpt.FormatEngine.ExportToStream(req)
pg.Response.ClearHeaders()
pg.Response.ClearContent()
pg.Response.ContentType = "application/pdf"
ReDim b(st.Length)
st.Read(b, 0, CInt(st.Length))
pg.Response.BinaryWrite(b)
pg.Response.End()
dt.Dispose()
Catch ex As Exception
ShowError(ex.Message)
End Try
End Sub
There is no way to accomplish this becuase you can't issue commands to the client from the server to make the computer print, it just doesn't work that way. There are ways to print using pdf's, but it is not very elegant and you stated you don't want to use pdfs...other than that I think you would have write some kind of browser plugin that would have to be installed on the machine that needs to print.
#AGoodDisplayName is mostly right. However, you don't give details of your environment - if you're building an intranet-based application, it is possible to have the server print directly to a printer, if that printer is accessible to the server.
There will be issues with security, and it will be a problem if you have many users with many printers, but it is possible.
Another option (if you have a captive audience with IE/Windows) is to run an "agent" process on the client machine. You can then have a web page "poke" that process with the data to be printed. In modern IE, the easiest way to do this is with APP (asynchronous pluggable protocols).
Without the "benefit" of IE/Windows, you're pretty much stuck with PDF.

Classic ASP DB opening function does not work

I have transferred a Classic asp site running on windows server 2003 to windows server 2008 but suddenly the below code has stopped working.
Const connStr_FC08 = "Provider=SQLNCLI10;Server=DS-47500;Database=TestDB;Uid=TestLogin;Pwd=test;Network=dbmssocn;"
Function connDB(OpenDB)
DIM conn
SET conn = Server.CreateObject("ADODB.Connection")
conn.open = connStr_FC08
If OpenDB = "Y" Then conn.open
connDB = conn
End Function
dim cn, cmd
cn = connDB("Y")
response.Write(cn.state)
This returns the below error
Microsoft VBScript runtime error '800a01a8'
Object required: 'Provider=SQLNCLI10.1'
This happens on the below line
response.write(cn.state)
Thanks
Chris
I see a few possible syntax issues with the code you posted:
...
conn.open = connStr_FC08
...
connDB = conn
...
cn = connDB("Y")
Should it be updated to the following?
...
conn.ConnectionString = connStr_FC08
...
Set connDB = conn
...
Set cn = connDB("Y")
You have that SQL Provider installed right?
You can put that function into a simple VBScript script to test without altering your pages any.
If I take opening of the connection out of the function and put in inline then there is no error and it works.
But my whole site works by using this function so a) I dont want to have to rewrite my code and b) I dont understand why this does not work when it used to.

Resources