VB.NET Linq to SQL - Query from table - vb.net

I am starting with Linq to SQL in VB.NET, and trying to figure out how to make a simple query to a database.
I want to do it all programaticly.
I have made a connection to the database with a connectionstring, and this works fine - I can get a message if the database exists or not.
But when I want to query a table, I am missing the part where I connest to the table. I have googled a lot to find an answer for thi, but
no luck. Can anyone point me in the right direction?
Code:
Dim strContactString, strDBServer, strDBName, strSQLUser, strSQLPW As String
strDBServer = "MyServer"
strDBName = "Northwind"
strSQLUser = "sa"
strSQLPW = "MyPW"
strContactString = ""
strContactString = strContactString & "data source=" & strDBServer & ";"
strContactString = strContactString & "initial catalog=" & strDBName & ";"
strContactString = strContactString & "user id=" & strSQLUser & ";"
strContactString = strContactString & "password=" & strSQLPW & ";"
Dim MyContext As New DataContext(strContactString)
'This works:
If MyContext.DatabaseExists Then
MsgBox("DB Exists")
Else
MsgBox("DB Does Not Exist")
End If
'This is the query I want to run (copied from samples I found)
Dim TEST = From c In MyContext.Customers _
Select c.ContactName
Error message:
'Customers' is not a member of 'System.Data.Linq.DataContext'.

First off you're not supposed to use DataContext directly.
You add a new dbml file to your project and map that to the database using the editor (this means connecting visual studio to your database, then dragging the tables you want from the server explorer to the dbml editor).
That will generate for you a class colled something like NortwindDataContext (you can control this from the properties pane in the editor).
You can then use that to write your queries:
Dim context As New DataContext(strContactString)
Dim TEST = From c In context.Customers _
Select c.ContactName

http://msdn.microsoft.com/en-us/library/bb399375.aspx
"Best practice is to declare a strongly typed DataContext instead of relying on the basic DataContext class and the GetTable method. A strongly typed DataContext declares all Table collections as members of the context, as in the following example."
As long as the db is connected correctly, this may be your problem.

Related

VB.net Receiving error BC30201: Expression expected

Im using this to declare a connection to a SQL
Public CONN As New SqlConnection("Data Source=" & My.Settings.SrvName & ";Initial Catalog=" & My.Settings.Catalog & ";Persist Security Info=" & True & ";User ID=" & My.Settings.USER & ";Password=" & My.Settings.PASSWRD & ";Integratedsecurity=" & My.Settings.InterSec & ";Connection Timeout=" & My.Settings.CnnTimeOut &)
but on the Closing ')' Im getting the error BC30201: Expression expected, this same method Ihave use in other proyects and works, can anyone tell me where my error?, please help.
Thanks.
This is a fine example of why lots of string concatenation is a bad idea. Your code is hard to read - even for you, obviously - and so it's error prone. With all those & operators in there, you haven't noticed that you have one you don't need at the end, This:
& My.Settings.CnnTimeOut &)
should be this:
& My.Settings.CnnTimeOut)
You should avoid using multiple & operators in one line and instead use the String.Format method or string interpolation. In this case, don't use any of those options. You should be using a SqlConnectionStringBuilder, e.g.
Dim builder As New SqlConnectionStringBuilder With {.DataSource = My.Settings.SrvName,
.InitialCatalog = My.Settings.Catalog}
Using connection As New SqlConnection(builder.ConnectionString)
'...
End Using
Notice that I have created the connection with a Using statement, which is what you should be doing too. Don't use a single, common connection. You can use a single connection string builder to generate the connection string, but you should then create, use and destroy connection objects where and when you need them.
Note that you can set as many properties of the connection string builder as you need to when you create it. I have just set two here for brevity.

Logs file into a database

So, I have an application where I am able to drop a file into a button and the information will be shown on my database. To make things better I am trying after add something a query will run with an INNER JOIN where there are 2 tables, one of them will simply save the files info and the other one will save the date and time of that added file. I already have the LogsFile method:
Private Sub LogFileAdicionados()
Dim LogsFile As String = My.Application.Info.DirectoryPath
Dim logtext As String = lblName.Text
Dim logtext2 As String = lblSize.Text
Dim vt As String = "The file " & logtext & " com " & logtext2 & " KB " & "was added at " & TimeOfDay & " in " & Date.Today & "." & vbCrLf
My.Computer.FileSystem.WriteAllText(LogsFile + "\LogsAdded.txt", vt, True)
End Sub
So what should I do to INSERT the data and time values onto the Logs table?
As Zaggler pointed out, you need at least to attempt to do it yourself in order to post more meaningful question. However I'm going to set you on the track and see what happen...
First you need an approach on how to interact with your database. I'll show you how to do it with ADO.NET data objects, but keep in mind that there are other tools/frameworks to interact with a DB storage.
Next you need the connection string to your database. You can find hundreds of examples here.
Then you can do some fun stuff, like:
Using conn As New SqlConnection("connection string to your DB goes here")
Using cmd = conn.CreateCommand()
cmd.CommandText = "INSERT INTO Logs (fields definition) VALUES" + vt
cmd.ExecuteNonQuery()
End Using
End Using
Basically this outlining saving data to a SQL DB, using ADO.NET data objects.

Unhandled Exception of Type System.Data.SqlClient SQL Exception in System.Data.dll

I am attempting to code a little Customer/sales database in VB. However on compiling I am getting the error stated in the subject. Apparently there is no connection to the database posible.
Here is the code I got so far:
Public Class Principal
Using Connect As SqlConnection =
Friend Sub CreateDatabase()
New SqlConnection("Data Source=(local);" &
"Integrated Security='SSPI';")
Dim strCreateDatabase As String = "IF EXISTS ( " &
"SELECT name " &
"FROM sys.databases " &
"WHERE name = N'BMSTIDB'" &
" ) " &
"DROP DATABASE BMSTIDB; " &
"CREATE DATABASE BMSTIDB"
Dim Command As SqlCommand =
New SqlCommand(strCreateDatabase, Connect)
Connect.Open()
Connect.ExecuteNonQuery()
MsgBox("A Database with the name of " &
"BMSTIDB has been created. ")
End Using
It compiles fine and it doens't display any errors or issues. However as mentioned above it does give the error upon running, when it first attempts to connect to the DB.
I am using Visual Studio 2015 Enterprise and Community.
Thanks a lot,
BenjB
New SqlConnection("Data Source=(local);" &
"Integrated Security='SSPI';Database=master")
You're missing a closing single quote here:
"WHERE name = N'BMSTIDB" &
It should be:
"WHERE name = N'BMSTIDB'" &
Once you fix that you'll find you're also missing the BEGIN and END keywords.

Q. How to dynamically add queries to a table adapter in Visual Studio

I have setup a Table Adapter in Visual Studio linked to a SQL Server db.
I've followed the MSDN tutorials and I have manually setup some queries for this TA. I think of these queries as "pre_hardcoded". I call these queries using the default code:
Me.ItemFactTableAdapter.My_Pre_Hardcoded_Query(Me.MasterDataSet.ItemFact)
I want to dynamically call data in different configuration (from the same Master Table) and thus I need a lot of these pre-hardcoded queries. So, instead of writing 1k queries I've want to use something like this:
TableName = "ItemFact"
H_Label = "ChainName"
V_Label = "ItemName"
Dim Measure As String = "Volume"
Dim Select_Clause As String = "select distinct " & H_Label & "," & V_Label & ", Sum(" & Measure & ") as " & Measure & " "
Dim From_Clause As String = "from " & TableName & " "
Dim Where_Clause As String = ""
Dim GroupBy_Clause As String = "group by " & H_Label & "," & V_Label
Dim SelectionQuery = Select_Clause & From_Clause & Where_Clause & GroupBy_Clause
Where I can dynamically update the values of "Measure" and the "H" & "V Labels".
The question is: How do I declare this SelectionQuery to be a valid part of the TA so that I can use it like:
Me.ItemFactTableAdapter.SelectionQuery (Me.MasterDataSet.ItemFact)
for dynamic query you need create generic DataAdapter:
Dim da As New SqlDataAdapter(SelectionQuery, Me.ItemFactTableAdapter.Connection)
da.Fill(Me.MasterDataSet.ItemFact)
I still haven't found an answer to my initial question ON HOW TO ADD QUERIES TO A TABLE ADAPTER, but based on #lomed answer I've done a workaround. Thus, instead of filling the TA on 1st load and then pulling data with different queries, I'm updating the whole dataset on each query. I believe this method may be more time-consuming when applied to big datasets, but for now it works.
Dim strConn As String = "Data Source=XXX;Initial Catalog=master;Integrated Security=True"
Dim conn As New SqlConnection(strConn)
Dim oCmd As New SqlCommand(SelectionQuery, conn)
Dim oData As New SqlDataAdapter(SelectionQuery, conn)
Dim ds As New DataSet
and then attach the dataset to objects like:
Chart1.DataSource = ds.Tables("Table1")
instead of:
Chart1.DataSource = Me.ItemFactBindingSource

ASP.NET error: Error 1 'isEqual' is not declared. It may be inaccessible due to its protection level

Hope there's .NET developers here that could enlighten me up.
I actually already made up some pages in .NET environment,
and i'm using VB.NET as my back-end.
Phewww....!
I have 2 files of A.ascx and B.ascx
and each of them have the A.ascx.vb and B.ascx.vb files altogether.
But here's the interesting part.
I use 'isEqual' variable inside one of the method I typed in.
And if I use it inside one of the vb file then, I could not use it into another vb file.
Thus, Once I used that 'isEqual' inside of these 2 vb (files), I will got the error appeared as from one of the vb file;
'isEqual' is not declared. It may be inaccessible due to its protection level.
Is there any alternative way out for this?
My code is actually this one;
Protected Sub bindTable()
'add somemore for searching with dropdown list
Dim sSql As String = "SELECT *, C.companyname FROM quotationmst Q"
Dim sColumn As String = Nothing
Dim sSearchField As String = Nothing
Dim sOptional As String = Nothing
If txtQuotationSearchField.Text.Length > 0 Then
sColumn = drpQuotationSearchField.SelectedItem.Value
sSearchField = " WHERE " & sColumn & " LIKE '%" & txtQuotationSearchField.Text & "%' "
sSql &= sSearchField
If isEqual(sColumn, "companyname") = 0 Or isEqual(sColumn, "customername") = 0 Then
sSearchField = " INNER JOIN customermst C on Q.customerid = C.customerid WHERE C." & sColumn & " LIKE '%" & txtQuotationSearchField.Text & "%'"
sSql &= sSearchField
End If
Else
sSearchField = " INNER JOIN customermst C ON Q.customerid = C.customerid"
sSql &= sSearchField
End If
Dim oCommon As New Common
sSql &= " ORDER BY quotationcode"
Dim dT As DataTable = oCommon.getDataSet(sSql)
dgRecord.DataSource = dT
dgRecord.DataBind()
lblTotal.Text = dT.Rows.Count
End Sub
Just do
If sColumn.Equals("companyname") Or sColumn.Equals("customername") Then
What I think is happening here is this:
When you create a file in Visual Studio (vb.net) and add a control using the designer it creates a file called "filename.aspx.designer.vb" You may have created the first page using the designer, and copied it to create the second page, losing the design file in that process.
This would give you the above error as the design file has auto generated field declarations in it, that look like this:
Protected WithEvents rptPackages As Global.System.Web.UI.WebControls.Repeater
In any case, try using the above declration for your vars, or at least make them "Protected" or "Public" so there is some kind of scope to them. Using dim can cause all kinds of runtime and compilation errors which are hard to diagnose because of type inferance.