Wrox Programmer Forums
Go Back   Wrox Programmer Forums > .NET > Other .NET > ADO.NET
|
ADO.NET For discussion about ADO.NET.  Topics such as question regarding the System.Data namespace are appropriate.  Questions specific to a particular application should be posted in a forum specific to the application .
Welcome to the p2p.wrox.com Forums.

You are currently viewing the ADO.NET section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old August 6th, 2004, 08:08 AM
Authorized User
 
Join Date: Aug 2004
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Default Example of a SQL Data Access Component ?

Can anyone let me have an example of SQL server "DataAccessCode.vb" that when compiled into a "DataAccessCode.dll" works succesfully. I am struggling to achieve this. I must be missing the appropiate class or connection syntax that works inside the .dll yet works fine when on the aspx page.

Andrew

 
Old August 6th, 2004, 11:40 PM
planoie's Avatar
Friend of Wrox
 
Join Date: Aug 2003
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts
Default

What does your class code look like for this file? I suspect that the problem might be in the way you are trying to consume the class. When you compile that file into a DLL, it will need to have a root namespace. I'm not sure what the compiler will give it for a root namespace if you don't explicitly provide one, but my guess is that it will create it as "DataAccessCode". So you therefore would need to access a class inside that .vb file like this:

DataAccessCode.ClassName
 
Old August 8th, 2004, 10:35 AM
Authorized User
 
Join Date: Aug 2004
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Here are all the files involved. I am completely stuck here. Note that the error shown suggests I am running asp.net 1.0 yet I think I have configured matrix to use asp.net 1.1. All this code is box standard from the book beginning ASP.NET 1.1 with vb 2003 EXCEPT for the fact I am trying to use the SQL data store of WroxUnited.
Please please can you get me help.
This is the DataAccessCode.vb that compiles to the .dll
-----------------------------------------------------------
Imports System
Imports System.Data
Imports System.Data.sqlClient
Imports System.Collections
Imports System.Configuration
imports System.Security

Namespace WroxUnited

    Public Class DataAccessCode
        Public Sub New()
        End Sub

        Function Dates() As System.Data.IDataReader
            Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionStrin g")
            Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionStri ng)
            Dim queryString As String = "SELECT [Games].[GameID], [Games].[Date] FROM [Games]"
            Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
            dbCommand.CommandText = queryString
            dbCommand.Connection = dbConnection
            dbConnection.Open
            Dim dataReader As System.Data.IDataReader = dbCommand.ExecuteReader(System.Data.CommandBehavio r.CloseConnection)
            Return dataReader
         End Function

     Function GamesByDate(ByVal [date] As Date) As System.Data.IDataReader
         Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionStrin g")
         Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionStri ng)
         Dim queryString As String = "SELECT [Teams].[TeamName], [Opponents].[OpponentName], [Games].[Location], [Oppon"& _
"ents].[OpponentLocation] FROM [Teams], [Opponents], [Games] WHERE (([Opponents]."& _
"[OpponentID] = [Games].[OpposingTeam]) AND ([Teams].[TeamID] = [Games].[WroxTeam"& _
"]) AND ([Games].[Date] = @Date))"
         Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
         dbCommand.CommandText = queryString
         dbCommand.Connection = dbConnection
         Dim dbParam_date As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
         dbParam_date.ParameterName = "@Date"
         dbParam_date.Value = [date]
         dbParam_date.DbType = System.Data.DbType.DateTime
         dbCommand.Parameters.Add(dbParam_date)
         dbConnection.Open
         Dim dataReader As System.Data.IDataReader = dbCommand.ExecuteReader(System.Data.CommandBehavio r.CloseConnection)
         Return dataReader
     End Function

    Function CheckFanEmailAddresses(ByVal fanEmail As String) As Boolean
        Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionStrin g")
        Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionStri ng)

        Dim queryString As String = "SELECT COUNT([Fans].[FanEmail]) FROM [Fans] WHERE ([Fans].[FanEmail] = @FanEmail)"
        Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
        dbCommand.CommandText = queryString
        dbCommand.Connection = dbConnection

        Dim dbParam_fanEmail As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
        dbParam_fanEmail.ParameterName = "@FanEmail"
        dbParam_fanEmail.Value = fanEmail
        dbParam_fanEmail.DbType = System.Data.DbType.String
        dbCommand.Parameters.Add(dbParam_fanEmail)
        Dim Result as Integer = 0
        dbConnection.Open
        Try
            Result = dbCommand.ExecuteScalar
        Finally
            dbConnection.Close
        End Try

        If Result > 0 then
            Return true
        else Return false
        End if

    End Function

    Function AddNewFanEmail(ByVal fanEmail As String) As Integer
        Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionStrin g")
        Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionStri ng)

        Dim queryString As String = "INSERT INTO [Fans] ([FanEmail]) VALUES (@FanEmail)"
        Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
        dbCommand.CommandText = queryString
        dbCommand.Connection = dbConnection

        Dim dbParam_fanEmail As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
        dbParam_fanEmail.ParameterName = "@FanEmail"
        dbParam_fanEmail.Value = fanEmail
        dbParam_fanEmail.DbType = System.Data.DbType.String
        dbCommand.Parameters.Add(dbParam_fanEmail)

        Dim rowsAffected As Integer = 0
        dbConnection.Open
        Try
            rowsAffected = dbCommand.ExecuteNonQuery
        Finally
            dbConnection.Close
        End Try

        Return rowsAffected
    End Function

    Function GetTeams() As System.Data.IDataReader
        Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionStrin g")
        Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionStri ng)

        Dim queryString As String = "SELECT [Teams].[TeamID], [Teams].[TeamName], [Teams].[Notes] FROM [Teams]"
        Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
        dbCommand.CommandText = queryString
        dbCommand.Connection = dbConnection

        dbConnection.Open
        Dim dataReader As System.Data.IDataReader = dbCommand.ExecuteReader(System.Data.CommandBehavio r.CloseConnection)

        Return dataReader

    End Function

    Function GetPlayersByTeam(ByVal teamID As Integer) As System.Data.IDataReader
        Dim connectionString As String = ConfigurationSettings.AppSettings("ConnectionStrin g")
        Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionStri ng)

        Dim queryString As String = _
        "SELECT [Players].[PlayerName], [Positions].[PositionName], [PlayerTeam].[TeamID] "& _
        "FROM [Players], [Positions], [PlayerTeam], [Teams] WHERE (([PlayerTeam].[PlayerI"& _
        "D] = [Players].[PlayerID]) AND ([PlayerTeam].[TeamID] = [Teams].[TeamID]) AND (["& _
        "PlayerTeam].[Position] = [Positions].[PositionID]) AND ([PlayerTeam].[TeamID] = "& _
        "@TeamID))"
        Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
        dbCommand.CommandText = queryString
        dbCommand.Connection = dbConnection

        Dim dbParam_teamID As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
        dbParam_teamID.ParameterName = "@TeamID"
        dbParam_teamID.Value = teamID
        dbParam_teamID.DbType = System.Data.DbType.Int32
        dbCommand.Parameters.Add(dbParam_teamID)

        dbConnection.Open
        Dim dataReader As System.Data.IDataReader = dbCommand.ExecuteReader(System.Data.CommandBehavio r.CloseConnection)

        Return dataReader
    End Function


    End Class
End Namespace


Quote:
quote:Originally posted by planoie
 What does your class code look like for this file? I suspect that the problem might be in the way you are trying to consume the class. When you compile that file into a DLL, it will need to have a root namespace. I'm not sure what the compiler will give it for a root namespace if you don't explicitly provide one, but my guess is that it will create it as "DataAccessCode". So you therefore would need to access a class inside that .vb file like this:

DataAccessCode.ClassName
-------------------------------------------------------
This is the web.config that contains the connection string
---------------------------------------------------------
        <appSettings>
            <add key="connectionString" value="server=(local)\WroxUnited; database=WroxUnited; integrated security=true" />
        </appSettings>

-----------------------------------------------------------
this is the codebehind default.aspx.vb page that calls the .dll
--------------------------------------------------------------
' Default.aspx.vb
'

Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.Caching
Imports System.DateTime
Imports System.Configuration
Imports System.Security
Imports WroxUnited

Namespace Wrox

    Public Class DefaultCodeBehind : Inherits Page

    Public DateList as New System.Collections.Hashtable()
    Public txtEmailAddress as Textbox
    Public lblRegister as Label
    Public btnRegister as Button
    Public pnlFixtureDetails as Panel
    Public MatchesByDateList as Repeater
    Public EventCalendar as Calendar
    Public Data as New DataAccessCode()

    sub Page_Load()
      if not page.ispostback

        if session("SelectedCss") is nothing then

            if request.cookies("PreferredCss") is nothing then
                Session("SelectedCss") = "WroxUnited.css"
            else
                Session("SelectedCss") = Request.Cookies("PreferredCSS").Value
            end if

        end if

      end if
         'The cache is now being used in order to stop having
         'to refresh the data each time the page is loaded
      if Cache("DateList") is nothing
         'we need to run this each time the page is loaded, so that
         'after a date is selected and the page is posted back, the
         'active dates will still be highlighted.
         dim DateReader as System.Data.iDataReader
         DateReader = Data.Dates()

         While DateReader.Read()
             DateList(DateReader("Date")) = DateReader("Date")
         end while
         DateReader.Close()

         Cache.Insert("DateList",DateList,nothing,DateTime. Now.AddMinutes(1), Cache.NoSlidingExpiration)
         Response.Write ("Added to Cache")
      Else
         Response.Write ("Already in Cache - nothing added")


      End if
         if not Request.cookies("EmailRegister") is nothing then
            txtEmailAddress.Visible = False
            lblRegister.Text = "You have registered for email updates"
            btnRegister.Visible = False
         end if
     end sub


         Sub EventCalendar_DayRender(sender As Object, e As DayRenderEventArgs)

           If Not Cache("DateList")(e.day.date) is Nothing then
             e.cell.cssclass = "SelectedDate"
             'e.cell.style.add("font-weight", "bold")
             'e.cell.style.add("font-size", "larger")
             'e.cell.style.add("border", "3 dotted darkred")
             'e.cell.style.add("background", "#f0f0f0")
             e.day.isselectable = true
           Else
             e.day.isselectable = false
             'e.cell.style.add("font-weight", "lighter")
             'e.cell.style.add("color", "DimGray")
           End If

         End Sub

         Sub EventCalendar_SelectionChanged(sender as object, e as eventargs)

             pnlFixtureDetails.visible=true
             MatchesByDateList.DataSource = Data.GamesByDate(EventCalendar.SelectedDate.ToShor tDateString)
             MatchesByDateList.DataBind()

         end sub

     Function Venue(OpponentLocation as string, MatchVenue as integer) as string

       If matchvenue = 1 then
        ' match is at home
         return "Wroxville"

       else
         return opponentlocation

       end if

     end function
' Dim connectionString As String = "server='(local)\WroxUnited'; trusted_connection=true; database='WroxUnited'"



    Sub btnRegister_Click(sender As Object, e As EventArgs)
        Dim FanMail as String = txtEmailAddress.Text

        'Check whether the email address is already registered
        'if not, we need to register it by calling the AddNewFanMail() method

        If Data.CheckFanEmailAddresses(FanMail) = false Then
            Data.AddNewFanEmail(FanMail)
        end if

        'Email has been registered, so update the display and attempt to set a
        'cookie

        txtEmailAddress.Visible = False
        lblRegister.Text = "You have successfully registered for email updates"
        btnRegister.visible = False

        Dim EmailRegisterCookie as New HttpCookie("EmailRegister")
        EmailRegisterCookie.Value = FanMail
        EmailRegisterCookie.Expires = now.AddSeconds(20)
        Response.Cookies.Add(EmailRegisterCookie)
    End Sub



    End Class
End Namespace
--------------------------------------------------------------
and finally here is the error that is created when the default.aspx page is run.
--------------------------------------------------------------

Server Error in '/' Application.
--------------------------------------------------------------------------------

Error loading XML file c:\windows\microsoft.net\framework\v1.0.3705\Confi g\machine.config Request for the permission of type System.Security.Permissions.StrongNameIdentityPerm ission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. (c:\windows\microsoft.net\framework\v1.0.3705\Conf ig\machine.config)
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.Configuration.ConfigurationException: Error loading XML file c:\windows\microsoft.net\framework\v1.0.3705\Confi g\machine.config Request for the permission of type System.Security.Permissions.StrongNameIdentityPerm ission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. (c:\windows\microsoft.net\framework\v1.0.3705\Conf ig\machine.config)

Source Error:


Line 46: 'active dates will still be highlighted.
Line 47: dim DateReader as System.Data.iDataReader
Line 48: DateReader = Data.Dates()
Line 49:
Line 50: While DateReader.Read()


Source File: C:\BegASPNet11\WroxUnitedSQLDataComponentFails\Def ault.aspx.vb Line: 48

Stack Trace:


[ConfigurationException: Error loading XML file c:\windows\microsoft.net\framework\v1.0.3705\Confi g\machine.config Request for the permission of type System.Security.Permissions.StrongNameIdentityPerm ission, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed. (c:\windows\microsoft.net\framework\v1.0.3705\Conf ig\machine.config)]
   System.Configuration.ConfigurationRecord.OpenXmlTe xtReader(String configFileName) +387
   System.Configuration.ConfigurationRecord.Load(Stri ng filename) +205
   System.Configuration.DefaultConfigurationSystem.Sy stem.Configuration.IConfigurationSystem.Init() +164
   System.Configuration.ConfigurationSettings.SetConf igurationSystem(IConfigurationSystem configSystem) +96
   System.Configuration.ConfigurationSettings.GetConf ig(String sectionName) +112
   System.Configuration.ConfigurationSettings.get_App Settings() +15
   WroxUnited.DataAccessCode.Dates() +8
   Wrox.DefaultCodeBehind.Page_Load() in C:\BegASPNet11\WroxUnitedSQLDataComponentFails\Def ault.aspx.vb:48
   System.Web.Util.ArglessEventHandlerDelegateProxy.C allback(Object sender, EventArgs e) +10
   System.Web.UI.Control.OnLoad(EventArgs e) +55
   System.Web.UI.Control.LoadRecursive() +21
   System.Web.UI.Page.ProcessRequestMain() +724




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:1.0.3705.288; ASP.NET Version:1.0.3705.288
 
Old August 9th, 2004, 03:59 AM
Authorized User
 
Join Date: Aug 2004
Posts: 21
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I have solved my problem using the Microsoft Community for webmatrix
thanks

 
Old August 9th, 2004, 06:26 AM
Friend of Wrox
 
Join Date: Jul 2004
Posts: 623
Thanks: 0
Thanked 1 Time in 1 Post
Default

wasn't your problem because of ....
Line 46: 'active dates will still be highlighted.
Line 47: dim DateReader as System.Data.iDataReader
Line 48: DateReader = Data.Dates()
Line 49:
Line 50: While DateReader.Read()
----
change iDataReader to IDataReader.
(it was a good sample for me it instructs how to pass a DataReader among several methods through it's interface,Thank you very much for your post)

--------------------------------------------
Mehdi.:)





Similar Threads
Thread Thread Starter Forum Replies Last Post
Microsoft Data Access Component (MDAC) Walden SQL Server 2000 3 September 4th, 2006 02:26 AM
Ch 10 :Data Access Component smsteven BOOK: Beginning Visual Basic 2005 Databases ISBN: 978-0-7645-8894-5 1 July 24th, 2006 05:09 PM
SQL Access/ASP.NET data access issue saeta57 SQL Server ASP 1 July 4th, 2004 04:29 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.