Object not queryable - asp.net

I have a database "Pubs" with a table "authors". I have made a dbml file from the database by dragging over "authors".
Here is the "Default.aspx.vb"
Public Class _Default
Inherits System.Web.UI.Page
Dim author As Object
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New PubsContext
Dim authors = From p In dbo.authors _
Select p
GridView1.DataSource = author
GridView1.DataBind()
End Sub
End Class
Here is the class for it: "Class1.vb"
Partial Public Class PubsContext
Dim authors As Object
Public Function GetProductsByCategory(ByVal id1 As Integer) As IEnumerable(Of authors)
Return From p In Me.authors _
Where p.au_id = id1 _
Select p
End Function
End Class
Error code:
"Expression of type 'Object' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ".
In references there is already a "System.Data.Linq". What should I do?

Well this is the problem:
Dim authors As Object
That's just an object. What does it mean to call Select, Where etc on that? Where are you even giving it a value? Work out what the type should really be, make sure you give it an appropriate value to start with, and you should be fine.
It's not clear why you're introducing your own authors field at all, to be honest - I'd expect the generated context to have an Authors property of type Table<Author> or something similar.
(I note that you're also trying to set GridView1.DataSource to author rather than authors, by the way... Why are you doing that? What value are you expecting the author field in _Default to have?)

Related

Trying to understand how SyncLock Works

I made a two static classes
NotInheritable Class gObject2
Public Shared TestSyncLock As String = "test"
End Class
NotInheritable Class gObject3
Public Shared TestSyncLock As String = "test"
End Class
Then I have two aspx
Synclock1.aspx:
Public Class SyncLock1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SyncLock gObject2.TestSyncLock
Thread.Sleep(10000)
End SyncLock
End Sub
End Class
Synclock2.aspx
Public Class SyncLock2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
SyncLock gObject3.TestSyncLock
SomeDiv.InnerHtml = "It works"
End SyncLock
End Sub
End Class
When I go to synclock1.aspx it spins for 10 seconds and shows a blank page as expected.
When I go to synclock2.aspx it spits out it works
Everything is good so far.
Now when I go to synclock1.apx and then in another browser got to synclock2.aspx, synclock2.aspx doesn't finish loading until synclock1.aspx finishes.
These are 2 different objects I'm locking with synclock, but it treats them the same. Why is this?
The SyncLockstatement takes an object reference as its argument. As the String type is a reference type, your code is satisfying that constraint. However, due to String Interning in .Net, the literal value equality of the two separate String references is also causing referential equality between gObject2.TestSyncLock and gObject3.TestSyncLock.
From: String.IsInterned Method - Remarks (emphasis added)
The common language runtime automatically maintains a table, called
the intern pool, which contains a single instance of each unique
literal string constant declared in a program, as well as any unique
instance of String you add programmatically by calling the Intern
method.
The intern pool conserves string storage. If you assign a literal
string constant to several variables, each variable is set to
reference the same constant in the intern pool instead of referencing
several different instances of String that have identical values.
Since both gObject2.TestSyncLock and gObject3.TestSyncLock are pointing to the same String reference, SyncLock gObject2.TestSyncLock will block SyncLock gObject3.TestSyncLock.
The subject code is a good example of how string interning can cause unexpected behavior. The article Interning Strings and immutability provides additional details on the mechanics of interning and also provides another example where interning can cause unexpected results.
So the moral of this story is to avoid using strings as the argument for SyncLock. It is safer to use something like the following:
NotInheritable Class gObject2
Public Shared TestSyncLock As New Object
End Class
NotInheritable Class gObject3
Public Shared TestSyncLock As New Object
End Class

LINQ query doesn't compile

Partial Class ProtectedContent_Books Inherits System.Web.UI.Page
Private database As BooksDataContext()
Protected Sub authorsLinqDataSource_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LinqDataSourceSelectEventArgs) Handles authorsLinqDataSource.Selecting
e.Result =
From author In database.Authors
Select Name = author.FirstName & " " & author.LastName, author.AuthorID()
End Sub
End Class
when I code From author In database.Authors it says Authors is not a member of System.Array!
The problem is that by
Private database As BooksDataContext()
you declare an array of BooksDataContext objects. I suspect you want to do:
Private database As New BooksDataContext()
This only declares one new instance of BooksDataContext.
You might also want to check the SELECT part of your query as it will not compile. If you want to select a new anonymous object, change your query as follows:
e.Result = From author In database.Authors
Select New With { .Name = author.FirstName & " " & author.LastName,
.AuthorId = author.AuthorID }
This link shows a sample on how to use the event.

How to persist an object in webform

As I'm self taught my VB coding is not bad but my use of OOP is poor. I'm sure this can be done but I have not found out how yet.
I am building a webforms app which needs to grab data about a user from AD. I have a Person Class which I can use as follows
Public Class _Default
Inherits System.Web.UI.Page
Dim LoggedOnPerson As Person 'Added here so available throughout class
Private strLoggedOnUser As String
Private strADDomain As String
Private strADUserID As String
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
strLoggedOnUser = Request.ServerVariables("LOGON_USER").ToUpper
strADDomain = strLoggedOnUser.Split("\")(0)
strADUserID = strLoggedOnUser.Split("\")(1)
If Not IsPostBack Then
'Dim LoggedOnPerson As Person *** changed to
LoggedOnPerson = New Person
'Get details from AD for logged on user
LoggedOnPerson.GetDetails(strADDomain, strADUserID)
'Store in Session
Session("LoggedOnUser") = LoggedOnUser
'This will now give me access to details such as
'LoggedOnPerson.EmailAddress
'LoggedOnPerson.GivenName
'LoggedOnPerson.TelephoneNo etc.
Else
'Postback so pull in details from Session
LoggedOnUser = Session("LoggedOnUser")
End If
End Sub
End Class
My problem is that I cannot access LoggedOnPerson in other events. e.g.
Public Sub SaveDetails()
Dim email As String = LoggedOnPerson.Email
'This now produces correct result. No error that LoggedOnPerson is not declared
End Sub
I of course get LoggedOnPerson is not declared error. How can I get around this.
You have created the object of "Person" inside Page_Load event. Take it outside and declare at the class level. Also add that object to view state/session state on Page_Load event and typecast it to "Person" class inside other events.

Untyped to strongly typed datatable

I tried to make some experiment today. I have an application that uses untyped datatables as the model entities.
They are all made like:
Imports System.Data
Imports System.Runtime.Serialization
Imports System.ComponentModel
<DesignerCategory("Code"), system.Serializable()>
Partial Public Class SomeTable1
Inherits DataTable
#Region
Public Const TABLE_NAME As String = "SomeTable1"
Public Const FIELD_SomeField1 As String = "SomeField1"
Public Const FIELD_SomeField2 As String = "SomeField2"
#End Region
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
Public Sub New()
MyBase.New()
With Columns
.Add(FIELD_SomeField1, GetType(System.String)).DefaultValue = String.Empty
.Add(FIELD_SomeField2, GetType(System.Double)).DefaultValue = 0
End With
Dim keys(1) As DataColumn
keys(0) = Columns(FIELD_SomeField1)
TableName = TABLE_NAME
PrimaryKey = keys
End Sub
End Class
I'm currently working with EF, so in my razzle, I wrote something like this (yeah, it's vb):
Partial Public Class SomeTable1
Inherits DataTable
<Key()>
Friend Property SomePK1 As DataColumn
<Required(ErrorMessage:="SomeField1 is required.")>
<DataType(DataType.Text)>
Friend Property SomeField1 As DataColumn
<Required()>
<DataType(DataType.DateTime)>
Friend Property SomeField2 As DataColumn
...
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
MyBase.New(info, context)
End Sub
Public Sub New()
MyBase.New()
SomeField2 = Date.Now
End Sub
End Class
I was dreaming on making something equivalent to the former dt and being completely compatible with the current data engine.
And then the type conversion error (system date to datacolumn) broke my hopes. I must admit that has been a hard weekend :)
So before I completely discard the change, Is there any way of writing a Typed datatable so it's equivalent to the code above but with some new goodies?
That's so ancient way of programming I can't find anything on the net.
Thanks in advance.
Not sure I'm following completely but it looks like you're defining FIELD_SomeField2 as a double
(This Line in first snippet)
.Add(FIELD_SomeField2, GetType(System.Double)).DefaultValue = 0
But then I see you're defining SomeField2 as a DateTime in your second snippet.
<Required()>
<DataType(DataType.DateTime)>
Friend Property SomeField2 As DataColumn
So maybe just a type mismatch...
I found how to do what I wanted. Perhaps involves some work, but it works.
Knowing that this is such an obsolete way of doing things, I'm posting there so others like me that are forced to maintain old programs can benefit.
The template for doing a typed datatable is the following:
Imports System.Data
Imports System.ComponentModel
Imports System.Runtime.Serialization
Imports System.Diagnostics
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class tblMyTable
Inherits TypedTableBase(Of tblMyTableRow)
'Those are the StoredProcs names for (MANUAL) CRUD operations that the DBContext wrapper uses. (yuck! I hate thousands of them)
'Public Const COMMAND_SAVE As String = "sp_MyTable_Save"
'Public Const COMMAND_DELETE As String = "sp_MyTable_Delete"
'Public Const COMMAND_LOADBY_ID As String = "sp_MyTable_LoadBy_Id"
'Those are constants I maintain for untyped (but somewhat strong) compatibility
Public Const FIELD_pID As String = "pID"
Public Const FIELD_SomeOther As String = "SomeOtherField"
'Basic CRUD, uses company data as the app hot swapps DBs (one for company)
'Public Function Save(ByVal company As DataRow) As Short
' Return New Base(company).Update(Me, COMMAND_SAVE, COMMAND_DELETE)
'End Function
'Public Sub LoadByID(ByVal company As DataRow, Id As Integer)
' Me.Rows.Clear()
' Me.Merge(New Base(company).FillDataTable(Of tblMyTable)(COMMAND_LOADBY_ID, Id))
'End Sub
<DebuggerNonUserCodeAttribute()>
Private Sub InitClass()
Me.columnpID = New DataColumn(FIELD_pID, GetType(Integer), Nothing, MappingType.Element) With
{.AllowDBNull = False, .ReadOnly = True, .Unique = True,
.AutoIncrement = True, .AutoIncrementSeed = -1, .AutoIncrementStep = -1}
MyBase.Columns.Add(Me.columnpID)
Me.columnSomeOtherField = New DataColumn(FIELD_SomeOther, GetType(String), Nothing, MappingType.Element) With
{.MaxLength = 5, .AllowDBNull = False, .DefaultValue = String.Empty}
MyBase.Columns.Add(Me.columnSomeOtherField)
End Sub
Private columnpID As DataColumn
Private columnSomeOtherField As DataColumn
<DebuggerNonUserCodeAttribute()>
Public Sub New()
MyBase.New()
Me.TableName = "tblMyTable"
Me.BeginInit()
Me.InitClass()
Me.EndInit()
End Sub
<DebuggerNonUserCodeAttribute()>
Friend Sub New(ByVal table As DataTable)
MyBase.New()
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<DebuggerNonUserCodeAttribute()>
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars()
End Sub
<DebuggerNonUserCodeAttribute()>
Public ReadOnly Property pIDColumn() As DataColumn
Get
Return Me.columnpID
End Get
End Property
<DebuggerNonUserCodeAttribute()>
Public ReadOnly Property SomeOtherFieldColumn() As DataColumn
Get
Return Me.columnSomeOtherField
End Get
End Property
<DebuggerNonUserCodeAttribute(), Browsable(False)>
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<DebuggerNonUserCodeAttribute()>
Default Public ReadOnly Property Item(ByVal index As Integer) As tblMyTableRow
Get
Return CType(Me.Rows(index), tblMyTableRow)
End Get
End Property
<DebuggerNonUserCodeAttribute()>
Public Overrides Function Clone() As DataTable
Dim cln As tblMyTable = CType(MyBase.Clone, tblMyTable)
cln.InitVars()
Return cln
End Function
<DebuggerNonUserCodeAttribute()>
Protected Overrides Function CreateInstance() As DataTable
Return New tblMyTable()
End Function
<DebuggerNonUserCodeAttribute()>
Friend Sub InitVars()
Me.columnpID = MyBase.Columns(FIELD_pID)
Me.columnSomeOtherField = MyBase.Columns(FIELD_SomeOther)
End Sub
<DebuggerNonUserCodeAttribute()>
Public Function NewtblMyTableRow() As tblMyTableRow
Return CType(Me.NewRow, tblMyTableRow)
End Function
<DebuggerNonUserCodeAttribute()>
Protected Overrides Function NewRowFromBuilder(ByVal builder As DataRowBuilder) As DataRow
Return New tblMyTableRow(builder)
End Function
<DebuggerNonUserCodeAttribute()>
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(tblMyTableRow)
End Function
<DebuggerNonUserCodeAttribute()>
Public Sub RemovetblMyTableRow(ByVal row As tblMyTableRow)
Me.Rows.Remove(row)
End Sub
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
Partial Public Class tblMyTableRow
Inherits DataRow
Private tabletblMyTable As tblMyTable
<DebuggerNonUserCodeAttribute()>
Friend Sub New(ByVal rb As DataRowBuilder)
MyBase.New(rb)
Me.tabletblMyTable = CType(Me.Table, tblMyTable)
End Sub
<DebuggerNonUserCodeAttribute()>
Public Property pID() As Integer
Get
Return CType(Me(Me.tabletblMyTable.pIDColumn), Integer)
End Get
Set(value As Integer)
Me(Me.tabletblMyTable.pIDColumn) = value
End Set
End Property
<DebuggerNonUserCodeAttribute()>
Public Property SomeOtherField() As String
Get
Return CType(Me(Me.tabletblMyTable.SomeOtherFieldColumn), String)
End Get
Set(value As String)
Me(Me.tabletblMyTable.SomeOtherFieldColumn) = value
End Set
End Property
End Class
That's all that you need. Perhaps It could be reduced, but then the dataset functions would not work as expected.
If you want that code, generated automagically for you by the ID (VS2010) you must follow those steps:
On server explorer, create the connection to your favorite DB
Right-click on top of your project and select adding a new element.
Just pick the dataset object template, the name is irrelevant. It will open in designer view.
Pick the table from the database and drag to the dataset designer.
Then... look at the class selector on top.
Unfold and locate [yourTableName]Datatable. Click on it.
It will jump to the said class in the DataSet1.designer.vb (cs) file.
The next class it's the row definition. Just copy-paste them into a new class file.
If you want a more complete datatable object, the next class below
the row class define events, and the delegate it's just above the
table def.
Simple and I tested it to work in conjunction of the remaining program, that uses untyped.
Perhaps it would be like polishing a turd, but I would like to add data annotations somewhere to do some client validations like in EF. And perhaps replace the columns constructor parameters for them. (but I caaan't)
good Luck.

Entity Framework - passing different object sets as a parameter in a function

I have the following code:
Private Sub setDropdowns()
Using licensingModel As New licensingEntities
SetUpDropdowns(licensingModel.tblLookup_Country, "CountryName", "CountryName", country)
SetUpDropdowns(licensingModel.tblLookup_Country, "CountryName", "CountryName", bizCountry)
SetUpDropdowns(licensingModel.tblLookup_Salutation, "SSalutation", "SSalutation", salutation)
SetUpDropdowns(licensingModel.tblLookup_OrgType, "OrgType", "OTAuto", organisationType)
End Using
End Sub
and the sub SetUpDropdowns:
Private Sub SetUpDropdowns(ByVal entity As IObjectSet(Of EntityObject), ByVal textColumn As String, ByVal valueColumn As String, ByVal combo As RadComboBox)
combo.DataSource = entity
combo.DataBind()
End Sub
My problem is that i dont know how to define the parameter type for the sub. Because they are different types of objectSets being passed each time, I thought IObjectSet(Of EntityObject) would work, but it gives me the following error:
Unable to cast object of type 'System.Data.Objects.ObjectSet1[licensingModel.tblLookup_Country]' to
type
'System.Data.Objects.IObjectSet1[System.Data.Objects.DataClasses.EntityObject]'‌
Would anyone have a solution for this?
can you not just use object as your parameter?

Resources