Why is "using" seemingly rejected in one function, but okay in another? - vb.net

With this code:
Protected Function GetArgValsForCompanyName(coName As String) As String()
Dim args(2) As String
Using con As New SqlConnection("SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=durante;PWD=pondscum"),
cmd As New SqlCommand("select Unit, MemberNo, CustNo from Customers WHERE CompanyName = #CoName", con)
con.Open()
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#CoName", SqlDbType.VarChar, 50).Value = coName
Using reader As SqlDataReader = cmd.ExecuteReader
While reader.Read
args(0) = reader.Item(0).ToString()
args(1) = reader.Item(1).ToString()
args(2) = reader.Item(2).ToString()
End While
End Using
End Using
Return args
End Function
...I get:
Server Error in '/EMS/customerreportingnet' Application.
--------------------------------------------------------------------------------
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30203: Identifier expected.
Source Error:
Line 94: Dim args(2) As String
Line 95:
Line 96: Using con As New SqlConnection("SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=durante;PWD=pondscum"),
Line 97: cmd As New SqlCommand("select Unit, MemberNo, CustNo from Customers WHERE CompanyName = #CoName", con)
Line 98:
Source File: C:\EnhancedMonthlySalesReporting\customerreportingnet\customerreportingnet\pages\custmaint_categoryadmin.aspx.vb Line: 96
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5491
So, the "using con" line is implicated as the problem. I commented out most of the code to just return some random values, and it works fine.
However, there is another "Using" being used: the Button1_Click event handler uses a using. Does it not complain only because the button has not been clicked?
Actually, when I click the button, I do get an error, but it's not about the using; it's because I apparently have too many controls on the form that the button deals with (thousands or label/checkbox pairs, in fact):
Server Error in '/EMS/customerreportingnet' Application.
--------------------------------------------------------------------------------
Operation is not valid due to the current state of the object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Operation is not valid due to the current state of the object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: Operation is not valid due to the current state of the object.]
System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() +4198079
System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) +60
System.Web.HttpRequest.FillInFormCollection() +189
[HttpException (0x80004005): The URL-encoded form data is not valid.]
System.Web.HttpRequest.FillInFormCollection() +11196408
System.Web.HttpRequest.get_Form() +119
System.Web.TraceContext.InitRequest() +1188
System.Web.TraceContext.VerifyStart() +133
System.Web.HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +11307449
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +452
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5491
So is it really the "using" that's the problem in the first block of code? Is there a way to still use it, or do I need to revert to the olde-[fangl,fashion]ed way of creating objects?

In VB.NET, the line continuation character allows to treat two lines as one from the point of view of the compiler. This character is the underscore and should be the last one on the line.
This requirement has been largely removed by latest version of VB.NET Compiler that has enough intelligence to understand where the statements end.
For example in LinqPAD 5.10 there is no need to use this character between the two using statement.
Instead, It seems that your current compiler cannot understand this and adding the continuation character should solve the problem
Using con As New SqlConnection("SERVER=PLATYPUS42;DATABASE=duckbilldata;UID=durante;PWD=pondscum"), _
cmd As New SqlCommand("select Unit, MemberNo, CustNo from Customers WHERE CompanyName = #CoName", con)

Related

OracleDataAdapter Started Returning error ORA-00942: table or view does not exist

Development Environment:
VB.NET
.net 4.5
ODP.NET
Oracle 11g
Hi there I have a weird problem, code in my development environment which has been working for a good number of years has suddenly stopped working. The OracleDataAdapter returns the error ORA-00942: table or view does not exist. However there is nothing wrong with the SQL that is passed to the adapter, the SQL executes successfully in SQLDeveloper. It looks like the issue is with my VS development environment, as a previously compiled version of the application runs as normal. I have re-compiled the entire VS solution and re-booted my development machine and then re-compiled without any joy.
The exact error returned is shown in the following log entry:
12|09:43:50|DOMAIN\USER|Trace| Oracle.DataAccess.Client.OracleException ORA-00942: table or view does not exist
at Microsoft.VisualBasic.CompilerServices.Symbols.Container.InvokeMethod(Method TargetProcedure, Object[] Arguments, Boolean[] CopyBack, BindingFlags Flags)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.ObjectLateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at QueryMain.uxBWFetch_DoWork(Object sender, DoWorkEventArgs e) in d:\users\USER\Documents_VSSWorkArea\PSALERTS 2017\PSALERTS Client\Query\QueryMain.vb:line 677
Here is the code which generates the error:
Dim myDataset As New DataSet
Dim myUtils As New Utils
_myConnection = New OracleConnection
_myConnection.ConnectionString = _connectStr
Try
_myDataAdapter = New OracleDataAdapter(SQLStatement, _myConnection)
_myDataAdapter.Fill(myDataset)
_myConnection.Close()
Catch ex As Exception
Throw
Finally
CType(_myConnection, IDisposable).Dispose()
End Try
Return myDataset
GC.Collect()
The error is generated when we try to fill the dataset:
_myDataAdapter.Fill(myDataset)
If anyone has encountered this situation could you please let me know, as it is driving me to distraction!!!
Kind Regards
Paul J.
Well now, don't I feel stupid. Turns out although my intention was to develop against our test database, the SQL generated within the code contained a hardcoded connect string which was pointing at production, and of course the code contains references to new tables which are not in production, hence the error message... DOH...

Could not load file or assembly 'MySqlBackup, Version=2.0.9.2

Consider:
Dim conn As MySqlConnection = New MySqlConnection(ServerString)
Dim cmd As MySqlCommand = New MySqlCommand
cmd.Connection = conn
conn.Open()
Dim mb As MySqlBackup = New MySqlBackup(cmd)
mb.ExportToFile("C:\backup.sql")
conn.Close()
I keep getting this error:
An unhandled exception of type 'System.IO.FileLoadException' occurred in System.Windows.Forms.dll
Additional information: Could not load file or assembly 'MySqlBackup, Version=2.0.9.2, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)
How can I fix this problem?
For now, one only can assume,
See the version actually referenced and used in the application.
Look in the .vbproj file for System.Windows.Forms,
If it exists, try removing this.
Build your solution on 32-bit and 64-bit one at a time and see if it works on either of them
Moreover, I assume number 1 and 3 can be, but I cannot be sure. Try it.
I fixed this problem, by uninstalling and reinstalling Visual Studio. Then I installed MySqlBackup.NET (using NuGet package manager) version 2.0.9.3, which automatically installed MySql.Data version 6.9.9. It works perfectly. I'm not saying that's the best solution, but it works.

Update Query from ASP.NET to .MDB Failing

Context:
I have an update query for a Microsoft Access DB that keeps failing. The query works when executed from within my DB, but fails when executed from my CodeFile for my .aspx page.
I have ensured that:
My App_Data folder has write permissions (via IUSR)
My DB is not 'Read Only'
My query syntax is correct
Does anyone have any advice on what I might be missing? Thank you!!
Code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Imports System.Data.OleDb
Partial Class jsDB
Inherits System.Web.UI.Page
Private con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\Dustin\App_Data\FAQ.accdb")
Public Sub Page_Load(sender as object, e as System.EventArgs)
If request.QueryString("type") = "helpful" Then
Dim cleanID as string
cleanID = request.querystring("id")
If IsNumeric(cint(cleanID)) Then 'Make sure QueryString hasn't been tampered with
Dim sql as string
sql = "UPDATE QUESTION SET helpful=helpful+1 WHERE questionID=" & cleanID
Dim cmd As New OleDbCommand(sql, con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Response.write("Success")
else
Response.write("Invalid ID")
end if
else
Response.write("No recognized type")
end If
End Sub
End Class
Error:
Server Error in '/' Application.
Operation must use an updateable query.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Operation must use an updateable query.
Source Error:
Line 27:
Line 28: con.Open()
Line 29: cmd.ExecuteNonQuery()
Line 30: con.Close()
Line 31:
Source File: C:\Dustin\FAQDB.aspx.vb Line: 29
Stack Trace:
[OleDbException (0x80004005): Operation must use an updateable query.]
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) +1102900
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +247
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +189
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) +58
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) +162
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() +107
jsDB.Page_Load(Object sender, EventArgs e) in C:\Dustin\FAQDB.aspx.vb:29
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
This help page addresses the error you are receiving:
https://support.microsoft.com/en-us/kb/175168
It looks like either youre not opening the connection in the right mode (Mode 3 in this case) or the "table" you are updating has conditions which prevent you from updating it. I'd bet though that changing your Mode to 3 will resolve the issue.
There are several things done wrong here that may help you resolve this and other issues in the future.
IsNumeric(cint(cleanID)) - The IsNumeric() on CInt() is irrelevant. The CInt will either return a System.Int32 or an error. You should just do the IsNumeric() and if you want to know if it is an Int32, then do a Int32.TryParse() on it.
Your command should be parameterized to avoid injection and to avoid passing the wrong data type. For example, I don't know if questionID is a string (which makes your syntax wrong) or if it is an int32. But, a parameterized command would and will supply the correct syntax to your SQL. You can find thousands of example on ho to do this so I will not explain it again here.
The last item, and likely the solution, MS Access queries like to end in a semicolon (;). Seems like I have had issues in the past with not having them in my UPDATE commands for MS Access.
As a side-note. MS Access is terrible about handling multiple connections so leaving them open because of errors will cause you HUGE problems. Be sure that all database calls have proper error handling and if you can put them in a USING block, even better.
Shout-out to #Steve for being such a big help on this.
I had several issues here. While I'm sure there are many issues which could produce the error I was experiencing, here's what resolved it for me:
Created a new application pool in IIS and gave this new pool write permissions to my App_Data folder
Assigned this new app pool to my application
Modified the new app pool under advanced settings to allow 32 bit applications
As of right now, the 'Microsoft.ACE.OLEDB.12.0' provider only works as 32-bit. Changing my application pool to allow 32 bit applications resolved the issue.
Thanks all for your input!

SQL Anywhere connection error: The driver doesn't support the version of ODBC behavior that the application requested

I'm trying to connect to a SQL Anywhere 5 database (I know it's olllld!) with a .NET 3.5 app in WinXP and it works fine from a stand alone console app. But when I run the exact code in a plugin ,running off a separate AppDomain, (the only difference I can tell between the two) with the following code, I get the errors further below.
BTW Both are executed as the SAME user.
using (OdbcConnection connection =
new OdbcConnection(strConnect))
{
OdbcCommand command = new OdbcCommand(query, connection);
command.CommandType = CommandType.Text;
DataTable posRecordsTable = new DataTable();
connection.Open();
OdbcException Exception returns the following errors:
Index #0
Message: [Sybase][ODBC Driver]Unable to connect to database server: database engine not running
Index #1
Message: [Sybase][ODBC Driver]Invalid connection string attribute
Index #2
Message: [Sybase][ODBC Driver]Invalid connection string attribute
Index #3
Message: [Microsoft][ODBC Driver Manager] The driver doesn't support the version of ODBC behavior that the application requested (see SQLSetEnvAttr).
Does the driver on your AppDomain have the same configuration as your stand alone box? I think checking the similarity of the environments will help you. Usually such errors are resolved by looking at the config files from where the driver reads its information. Dont know much about SQL Anywhere, but in general, I've come across such issues and I fixed them by altering the connection information or the configuration file.

SQL Statement help in vb.net

Sub Bind_dgList()
Dim strCommand As String
Dim strConnect As String
Dim DBDataAdapter_Leads As OleDbDataAdapter
Dim DBConnection_List As OleDbConnection
Dim DBDataSet_Leads As DataSet
Dim DBDataView_Leads As DataView
strConnect = GetDBConnectionString()
DBConnection_List = New OleDbConnection(strConnect)
strCommand = "SELECT * Manager FROM tblList ORDER BY Names"
DBDataAdapter_Leads = New OleDbDataAdapter(strCommand, DBConnection_List) DBDataSet_Leads = New DataSet
DBDataAdapter_Leads.Fill(DBDataSet_Leads, "tblList")
DBDataView_Leads = New DataView(DBDataSet_Leads.Tables("tblList"))
dgList.DataSource = DBDataView_Leads
dgList.DataBind()
End Sub
Can anyone help me with the above code? I want to select distinct record of names. Some of the names are repeating. May I know how to do it?
I have used all the above. But There is an error showing.
First error : Server Error in '/wwwroot' Application. Syntax error (missing operator) in query expression '* Manager'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Syntax error (missing operator) in query expression '* Manager'.
Source Error: Line 71: DBDataAdapter_FocalLeads = New OleDbDataAdapter(strCommand, DBConnection_AgentList) Line 72: DBDataSet_FocalLeads = New DataSet Line 73: DBDataAdapter_FocalLeads.Fill(DBDataSet_FocalLeads, "tblAgentList") Line 74: DBDataView_FocalLeads = New DataView(DBDataSet_FocalLeads.Tables("tblAgentList"))
Line 75:
Second Error : DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'FieldId'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'FieldId'.
Source Error: Line 75: Line 76: dgAgentList.DataSource = DBDataView_FocalLeads Line 77: dgAgentList.DataBind() Line 78: End Sub
Line 79:
But When am using this there is no error, but the manager names are repeating. strCommand = "SELECT * FROM tblAgentList ORDER BY Manager"
Am doing this to mass edit and update the records. If I can get help in doing the mass updating I can ignore this page. Now I have to edit line by line. So if there is change in a managers role and its repeating 5 times. I need to manually edit one by to update. So is there a way to do a mass update?
Thank you for the help.. I really appreciate.. :)
I have used all the above. But There is an error showing.
First error : Server Error in '/wwwroot' Application.
Syntax error (missing operator) in query expression '* Manager'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Syntax error (missing operator) in query expression '* Manager'.
Source Error:
Line 71: DBDataAdapter_FocalLeads = New OleDbDataAdapter(strCommand, DBConnection_AgentList)
Line 72: DBDataSet_FocalLeads = New DataSet
Line 73: DBDataAdapter_FocalLeads.Fill(DBDataSet_FocalLeads, "tblAgentList")
Line 74: DBDataView_FocalLeads = New DataView(DBDataSet_FocalLeads.Tables("tblAgentList"))
Line 75:
Second Error : DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'FieldId'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'FieldId'.
Source Error:
Line 75:
Line 76: dgAgentList.DataSource = DBDataView_FocalLeads
Line 77: dgAgentList.DataBind()
Line 78: End Sub
Line 79:
But When am using this there is no error, but the manager names are repeating.
strCommand = "SELECT * FROM tblAgentList ORDER BY Manager"
Am doing this to mass edit and update the records. If I can get help in doing the mass updating I can ignore this page.
Now I have to edit line by line. So if there is change in a managers role and its repeating 5 times. I need to manually edit one by to update. So is there a way to do a mass update?
Thank you for the help.. I really appreciate.. :)
Did you mean:
SELECT * FROM Manager tblList ORDER BY Names
or
SELECT *, Manager FROM tblList ORDER BY Names
?
Modify your SQL statement like this
SELECT DISTINCT Names FROM Manager
ORDER BY Names
I don't think
SELECT * FROM
will work.
Assuming the rest of the code works all you should need to do is change this line
strCommand = "SELECT * Manager FROM tblList ORDER BY Names"
to this
strCommand = "SELECT DISTINCT * Manager FROM tblList ORDER BY Names"