Author Topic: ASP.NET/VB men of GATT, could use a little help here.  (Read 3893 times)

Offline Spazosaurus

  • Dr. Herp Derpington
  • Administrator
  • Akatsuki
  • *****
  • Posts: 7685
  • Country: tt
  • Chakra 52
  • Referrals: 3
    • View Profile
    • The Awesome Company
  • CPU: i5 3470
  • GPU: GTX 780
  • RAM: 8GB Corsair
  • Broadband: Blink 2Mb + Flow 20Mb
ASP.NET/VB men of GATT, could use a little help here.
« on: February 27, 2011, 12:26:58 PM »
So I was in class yesterday and the lecturer was going through how to interface a normal access database with aspx in Visual Studio 2010.

SO we have an access database with a table called 'departments' with the fields 'departmentid' and 'departmentname'

This is the code for the actual web page, a 'form' with an 'id' and 'department' field and a submit button that will throw entered data directly into the database.

Quote
<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="AddDepartment.aspx.vb" Inherits="AddDepartment" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<table>
    <tr>
        <td><asp:Label ID="lblmessage" runat="server" Text=""></asp:Label></td>
    </tr>
    <tr>
        <td>ID</td>
        <td><asp:TextBox ID="txtid" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
        <td>Name</td>
        <td><asp:TextBox ID="txtname" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
        <td colspan="2"><asp:Button ID="btnadd" runat="server" Text="Add" /></td>
    </tr>
</table>

</asp:Content>

Ok, so I can follow that code. Now here's the aspx.vb code...

Quote
Partial Class AddDepartment
    Inherits System.Web.UI.Page

    Protected Sub btnadd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnadd.Click

        Dim id As String
        Dim name As String

       id = txtid.Text
        name = txtname.Text

        DBDepartmentController.Create(id, name)

    End Sub

    Protected Sub txtid_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtid.TextChanged

    End Sub

    Protected Sub txtname_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtname.TextChanged

    End Sub
End Class

Now this is where things start getting tricky. The higlighted lines there I can make sense of...kind of...'id' and 'name' are te two fields in the database. What I dont understand is how the code will know which database to go to and what table to put data in. It should be noted that the database is already added to the solution.

So I asked a question and he said right click on the code and press 'go to definition'

When I did that, I got this...

Quote
Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.OleDb

Public Class DBDepartmentController

    'create
    'read
    'update
    'delete

    Public Shared Function Create(ByVal USER ID As String, ByVal Name As String)

        Dim cmdText As String
        cmdText = "INSERT INTO USERS VALUES('{0}','{1}')"

        Dim myConnection As OleDbConnection
        myConnection = DBController.GetConnection()

        Dim myCommand As New OleDbCommand
        myCommand.Connection = myConnection
        myCommand.CommandText = String.Format(cmdText, ID, Name)

        myCommand.ExecuteNonQuery()

    End Function

    Private Shared Function ID() As Object
        Throw New NotImplementedException
    End Function


End Class

Now this makes a little more sense. You see the UML 'INSERT INTO USERS VALUES '{0}',  '{1}'. What the hell does that mean? Before I could ask another question homeboy was gone leaving my classmates in a similar puzzled state.

So I still not sure where to go from here. Help me to understand how he is getting this code to input data from a web form directly into the access db tables. Please?


Carigamers

ASP.NET/VB men of GATT, could use a little help here.
« on: February 27, 2011, 12:26:58 PM »

Offline Eroo

  • Kage
  • ****
  • Posts: 1093
  • Country: tt
  • Chakra 35
    • PSX,PS2,PSP,PS3,PS4
  • Referrals: 1
    • View Profile
  • CPU: Intel i7 5820k
  • GPU: Gigabyte Geforce GTX 980 Ti
  • RAM: 32GB Corsair Vengeance LPX DDR4
  • Broadband: Flow/Blink
  • PSN: David_Crockett
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #1 on: February 27, 2011, 12:46:08 PM »
Well I've never used asp or Visual Studio but it looks like the code is making a ole connection. This line

myConnection = DBController.GetConnection()

looks it selects the active connection.

Check and see if there is an option to see connection string or oledbconnection. That might give u the connection string to the access db.

Also the line

INSERT INTO USERS VALUES('{0}','{1}')

is a sql statement to insert into a table called USERS.


Again I may be incorrect and someone who is familiar with these programs may offer better insight.

Offline UltimateGamer

  • Kage
  • ****
  • Posts: 1366
  • Country: 00
  • Chakra 40
  • The Great Sage!
    • WD CGreen 1TB + 2TB + 2.5TB + WD CBlack 1TB + Dell 24&quot; 1080p Monitor
  • Referrals: 0
    • View Profile
    • Access Control Trinidad
  • CPU: MSI P55-GD80 + Core i5 750 + cooler master hyper 212+ dual fan
  • GPU: xfx HD6870
  • RAM: 12 GB Corsair vengeance DDR3 1600mhz
  • Broadband: :flow:
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #2 on: February 27, 2011, 05:01:13 PM »
LOL All that fightup hoss:


Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.OleDb

Public Class DBDepartmentController

    'create
    'read
    'update
    'delete

    Public Shared Function Create(ByVal USER ID As String, ByVal Name As String)

        Dim cmdText As String
/*

Quite obviously this is the insert query. The values {0} and {1} are a set of ordered placeholders, usually applicable to String datatype and usually found in the String.Format method
*/
        cmdText = "INSERT INTO USERS VALUES('{0}','{1}')"

        Dim myConnection As OleDbConnection
        myConnection = DBController.GetConnection()

        Dim myCommand As New OleDbCommand
        myCommand.Connection = myConnection

/*
This is where the magic happens:

We pass the sql query into the commandText property of the OleDbCommand, listed as the myCommand instance. The SQL query (cmdText variable) is passed into the String.Format() method. Followed by the 2 parameters in the sequence specified in the cmdText variable.

So String.Format (cmdText, {0}, {1}) is essentially the method that is being called.

Thus
myCommand.CommandText = "INSERT INTO USERS VALUES('ID','Name')" , since {0}=> ID and {1}=> mapped unto Name.

*/
        myCommand.CommandText = String.Format(cmdText, ID, Name)

        myCommand.ExecuteNonQuery()

    End Function

    Private Shared Function ID() As Object
        Throw New NotImplementedException
    End Function


End Class

Some additional notes. The reason they did it like this, is that String.Format assist the readability of your code. This would have also been correct:

myCommand.CommandText = "INSERT INTO USERS VALUES('"+ID+"','"+Name+"')"

exactly as it is written here.

Notice however the use of quotes and concatenations. The code looks a little scrappy. Also imagine having to use the same query more than once in this method, you will have to rewrite that insert command numerous times.

Now the String.Format advantage

cmdText = "INSERT INTO USERS VALUES('{0}','{1}')"

myCommand.CommandText = String.Format(cmdText, ID, Name)

Notice the readability and no complex concatenations. And in a multiple query instance: we could have this:

myCommand.CommandText = String.Format(cmdText, 1, "Crixx")
myCommand.CommandText = String.Format(cmdText, 2, "Hard")
myCommand.CommandText = String.Format(cmdText, 3, "Ulti")
myCommand.CommandText = String.Format(cmdText, 4, "Eroo")

instead of

myCommand.CommandText = "INSERT INTO USERS VALUES(1,'Crixx')"
myCommand.CommandText = "INSERT INTO USERS VALUES(2,'Hard')"
myCommand.CommandText = "INSERT INTO USERS VALUES(3,'Ulti')"
myCommand.CommandText = "INSERT INTO USERS VALUES(4,'Eroo')"

I hope that clears up exactly what is taking place here. You can PM me if you have anymore questions or you are unclear of anything

   

Offline UltimateGamer

  • Kage
  • ****
  • Posts: 1366
  • Country: 00
  • Chakra 40
  • The Great Sage!
    • WD CGreen 1TB + 2TB + 2.5TB + WD CBlack 1TB + Dell 24&quot; 1080p Monitor
  • Referrals: 0
    • View Profile
    • Access Control Trinidad
  • CPU: MSI P55-GD80 + Core i5 750 + cooler master hyper 212+ dual fan
  • GPU: xfx HD6870
  • RAM: 12 GB Corsair vengeance DDR3 1600mhz
  • Broadband: :flow:
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #3 on: February 27, 2011, 05:11:23 PM »
LOL - First Development Job: 2 years Senior VB.NET Developer.

Been almost 2 years since I touched MS technology. PHP is my server side language of choice now. But its good to know that I'm not a complete retard in something I was once great at.
   

Offline Spazosaurus

  • Dr. Herp Derpington
  • Administrator
  • Akatsuki
  • *****
  • Posts: 7685
  • Country: tt
  • Chakra 52
  • Referrals: 3
    • View Profile
    • The Awesome Company
  • CPU: i5 3470
  • GPU: GTX 780
  • RAM: 8GB Corsair
  • Broadband: Blink 2Mb + Flow 20Mb
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #4 on: February 27, 2011, 06:21:11 PM »
Thanks for your response Ulti, I think I understand what you say. Basically the ('{0}','{1}')" serve as an index or table of contents for the code instead of listing everything out.

What I still dont get is how the code is able to know what database to look in, what table and what fields to insert data into.

Carigamers

Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #4 on: February 27, 2011, 06:21:11 PM »

Offline UltimateGamer

  • Kage
  • ****
  • Posts: 1366
  • Country: 00
  • Chakra 40
  • The Great Sage!
    • WD CGreen 1TB + 2TB + 2.5TB + WD CBlack 1TB + Dell 24&quot; 1080p Monitor
  • Referrals: 0
    • View Profile
    • Access Control Trinidad
  • CPU: MSI P55-GD80 + Core i5 750 + cooler master hyper 212+ dual fan
  • GPU: xfx HD6870
  • RAM: 12 GB Corsair vengeance DDR3 1600mhz
  • Broadband: :flow:
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #5 on: February 27, 2011, 06:51:30 PM »
Ok, essentially as for the database to look in, there are several ways to do so. Chances are the connection data is stored in the web.config file (if i remember carefully). Now based on the code you supplied, it seems like the connection information (meaning host, username, password and dbname) is stored in the class DBController and retrieved by use of the method GetConnection(), thus we have the line:

myConnection = DBController.GetConnection()

Now myConnection is of Type OleDbConnection, which i am pretty sure takes parameters, such as the connections string information. So if you wanted to connect to a different database that the one that you have set in you application config datasource, you can supply the additional parameters there:

Dim myConnString As String = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;Connect Timeout=30"

Dim myConnection As New OleDbConnection(myConnString)
or
Dim myConnection = New OleDbConnection(myConnString)
or just
Dim myConnection = New OleDbConnection("Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;Connect Timeout=30")

All are correct. But you can see here, that the OleDbConnection is how we connect to the database/specify what we want to connect to. Lucky for you the application config store the connection information and allows you to connect directly to the datasource using the
DBController.GetConnection() method. The one thing you will notice about MS technology is that they try to automate/make things as easy as possible for developers.

As for what table to look/insert into, that is in the SQL query which is stored in the following statement:

cmdText = "INSERT INTO USERS VALUES('{0}','{1}')"

SQL 101 =>
'INSERT INTO' => Tell the method what action/query type
'USERS' => This is the table name you were asking about['b]
'VALUES' => This is how you specify the parameters/Fields you wish to insert.

You of course will need to have a defined database, and know the datastructure in order to write a query to execute in its context.

And that brings the 3rd part (what fields)

That is where you specify the 'VALUES ({0},{1})

So essentially, you have a table departments with 2 columns/fields departmentid and departmentname

Your SQL query is how the code knows how to enter the data! How your query is written is not wrong, but just a bad idea (I know its not yours per say). In your SQL query, you should always define your data structure, and anyone tells you otherwise, they are either an ass or ignorant. Reason being, if you change your datastructure, your code WILL NOT BREAK.

So lets see how you query should look:

cmdText = INSERT INTO USERS(departmentid, departmentname) VALUES('{0}','{1}')"!

how it is originally, by default the sql executor ascribes {0} to column 1 and {1} to column 2. Now if you move departmentname down 1 place and replace it with departmenttype, then the value {1} will now be mapped to departmenttype instead of departmentname!!! Now your code breaks! But because in the above query we listed explicitly which fields you want to go where, you are no longer in danger of such a senario (unless you delete the field of course)

In the following post I will try to go through all your code and comment them accordingly so you can always reference it if you are having trouble in the future.
   

Offline UltimateGamer

  • Kage
  • ****
  • Posts: 1366
  • Country: 00
  • Chakra 40
  • The Great Sage!
    • WD CGreen 1TB + 2TB + 2.5TB + WD CBlack 1TB + Dell 24&quot; 1080p Monitor
  • Referrals: 0
    • View Profile
    • Access Control Trinidad
  • CPU: MSI P55-GD80 + Core i5 750 + cooler master hyper 212+ dual fan
  • GPU: xfx HD6870
  • RAM: 12 GB Corsair vengeance DDR3 1600mhz
  • Broadband: :flow:
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #6 on: February 27, 2011, 07:21:47 PM »

<!--This is how you write comments in html-->

<!--This is the aspx page declaration. It is usually generated by VS for you. It stores config options, and the path of the backend/ server side scripts.
In this case, your server page is defined by using the CodeFile Attr, and as we can see it is: AddDepartment.aspx.vb

Note. Don't be fooled into thinking that the codefile must be seperate to this html file. It can reside on the same page but for readablity sake, its much better to do it this way.
-->
<%@ Page Title="" Language="VB" MasterPageFile="~/Site.master" AutoEventWireup="false" CodeFile="AddDepartment.aspx.vb" Inherits="AddDepartment" %>

<!--These tags render as divs
What is important to note is the runat="server" attribute. This makes that location accessible from the serverside code, and allows vs to bring it up in the autocomplete.
-->
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<table>
    <tr>
        <td>
        <!--renders as span-->
        <asp:Label ID="lblmessage" runat="server" Text=""></asp:Label></td>
    </tr>
    <tr>
        <td>ID</td>
        <td>
        <!--Renders as input type='text'-->
        <asp:TextBox ID="txtid" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
        <td>Name</td>
        <td><asp:TextBox ID="txtname" runat="server"></asp:TextBox></td>
    </tr>
    <tr>
        <td colspan="2">
        <!--Renders as input type = 'button' (or) type= 'submit' if the page is a webform-->
        <asp:Button ID="btnadd" runat="server" Text="Add" /></td>
    </tr>
</table>

</asp:Content>

/*
This is C# comment syntax. VB.Net does not allow multiline comments so it makes it difficult to type this tutorial out.
*/

/*
This is your page backend
*/
Partial Class AddDepartment
    Inherits System.Web.UI.Page

    /*
    This is the event handler for the click event on the "btnadd" field on your web form. When it is clicked, this method is fired!
    */
    Protected Sub btnadd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnadd.Click

    'These are variable declarations
        Dim id As String
        Dim name As String
       
    'Grab the Text value that exist in "txtid" field on the webform (aspx page)
        id = txtid.Text
       
    'Grab the Text value that exist in the "txtname" field on the webform (aspx page)
        name = txtname.Text

    'We now call a method to insert the data in the database
        DBDepartmentController.Create(id, name)
   
    /*
    Note: From what i am seeing here, it is following a simple MVC pattern, where your database logic is stored in a seperate file known as a controller. DBDepartmentController is the name of the class which seems to contain the logic by which to create the database entry.
    */

    End Sub

    'This fuction will execute if you change the value in the 'txtid' field
    Protected Sub txtid_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtid.TextChanged

    End Sub

    'This fuction will execute if you change the value in the 'txtname' field
    Protected Sub txtname_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtname.TextChanged

    End Sub
   
End Class


'Import the crucial Classes required for executing the page logic.
Imports Microsoft.VisualBasic
'The classes for handling data connections
Imports System.Data
Imports System.Data.OleDb

/*
As mentioned previously, this class handles the db logic
*/
Public Class DBDepartmentController

    'create
    'read
    'update
    'delete
   
/*
This method creates a new entry in the database! It takes 2 parameters
User Id (this is the txtid field from the webform) PS that syntax seems incorrect (missing an underscore perhaps USER_ID or simply ID based on the values in the method {I removed the USER ID and replaced it with just ID to match})
Name (this is the txtname field from the webform)
*/
    Public Shared Function Create(ByVal ID As String, ByVal Name As String)

    'Write the insert sql
        Dim cmdText As String
   
    /*
    As mentioned previously, this should be ammended to allow the fieldnames to appear with its corresponding fieldvalue
    cmdText = INSERT INTO USERS(departmentid, departmentname) VALUES('{0}','{1}')"!
   
    */
        cmdText = "INSERT INTO USERS VALUES('{0}','{1}')"

        'Make a new connection to an OleDB Data source (MS Access)
        Dim myConnection As OleDbConnection
       
        'Connect to the database using a connection string previously set by the application config!
        myConnection = DBController.GetConnection()

        'A command is required to execute a database query. All sql queries go through the class Command (OleDbCommand, SqlCommand etc)
        Dim myCommand As New OleDbCommand
       
        'Specify the connection to which the command will be routed (Defined above)
        myCommand.Connection = myConnection
       
        /*Specify the sql to execute. (Our sql is stored in the cmdText variable, and it is missing 2 parameters ({0} and {1}). These parameters are defined in the method definition ID and Name, which comes from the webform)
       
        After the String.Fomat method runs, myCommand.CommandText = INSERT INTO USERS(departmentid, departmentname) VALUES(ID,Name)"
        */
        myCommand.CommandText = String.Format(cmdText, ID, Name)

        'Execute query (Does not return any values *I believe)
        myCommand.ExecuteNonQuery()

    End Function

    Private Shared Function ID() As Object
        Throw New NotImplementedException
        'This is invalid, no use for this at this time
    End Function


End Class

I surely hope this in addition with what we discussed earlier has cleared up any issues you may be having.

Peace :)
   

Offline Spazosaurus

  • Dr. Herp Derpington
  • Administrator
  • Akatsuki
  • *****
  • Posts: 7685
  • Country: tt
  • Chakra 52
  • Referrals: 3
    • View Profile
    • The Awesome Company
  • CPU: i5 3470
  • GPU: GTX 780
  • RAM: 8GB Corsair
  • Broadband: Blink 2Mb + Flow 20Mb
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #7 on: February 27, 2011, 09:19:03 PM »
Wow. Thanks for your input.

I'm just now trying to run the same code that he gave us and now its giving me an 'oledb not registered on the local machine' error. Just abt ready to cry myself to sleep off of this thing. Google is...less than helpful for me in this matter.

I need some serious one on one classes for this thing. Any recommendations?

Offline TriniXaeno

  • Administrator
  • Akatsuki
  • *****
  • Posts: 18836
  • Country: tt
  • Chakra 14
    • :ps3::wii::xbox360:
  • Referrals: 35
    • View Profile
    • http://www.carigamers.com
  • CPU: Intel Core i7-2600K
  • GPU: Geforce GTX 680 2GB
  • RAM: 16GB
  • Broadband: :flow:
  • MBL: Nexus 5x
  • PSN: TriniXaeno
  • XBL: TriniXaeno
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #8 on: February 28, 2011, 12:11:09 AM »
that is what does happen when technicians take programmer courses.

Stick to A+ lol

Offline Spazosaurus

  • Dr. Herp Derpington
  • Administrator
  • Akatsuki
  • *****
  • Posts: 7685
  • Country: tt
  • Chakra 52
  • Referrals: 3
    • View Profile
    • The Awesome Company
  • CPU: i5 3470
  • GPU: GTX 780
  • RAM: 8GB Corsair
  • Broadband: Blink 2Mb + Flow 20Mb
Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #9 on: February 28, 2011, 07:15:13 AM »
Lol @ wyatt.

Well google did help with the The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine error. I installed the office 2007 data components and now the thing works as it should. Going to look at the code again, see if I can get it working.

Thanks a lot guys i'll post back with more questions within the next couple days.

Carigamers

Re: ASP.NET/VB men of GATT, could use a little help here.
« Reply #9 on: February 28, 2011, 07:15:13 AM »

 


* ShoutBox

Refresh History
  • Crimson609: yea everything cool how are you?
    August 10, 2022, 07:26:15 AM
  • Pain_Killer: Good day, what's going on with you guys? Is everything Ok?
    February 21, 2021, 05:30:10 PM
  • Crimson609: BOOM covid-19
    August 15, 2020, 01:07:30 PM
  • Shinsoo: bwda 2020 shoutboxing. omg we are in the future and in the past at the same time!
    March 03, 2020, 06:42:47 AM
  • TriniXjin: Watch Black Clover Everyone!
    February 01, 2020, 06:30:00 PM
  • Crimson609: lol
    February 01, 2020, 05:05:53 PM
  • Skitz: So fellas how we go include listing for all dem parts for pc on we profile but doh have any place for motherboard?
    January 24, 2020, 09:11:33 PM
  • Crimson609: :ph34r:
    January 20, 2019, 09:23:28 PM
  • Crimson609: Big up ya whole slef
    January 20, 2019, 09:23:17 PM
  • protomanex: Gyul like Link
    January 20, 2019, 09:23:14 PM
  • protomanex: Man like Kitana
    January 20, 2019, 09:22:39 PM
  • protomanex: Man like Chappy
    January 20, 2019, 09:21:53 PM
  • protomanex: Gyul Like Minato
    January 20, 2019, 09:21:48 PM
  • protomanex: Gyul like XJin
    January 20, 2019, 09:19:53 PM
  • protomanex: Shout out to man like Crimson
    January 20, 2019, 09:19:44 PM
  • Crimson609: shout out to gyal like Corbie Gonta
    January 20, 2019, 09:19:06 PM
  • cold_187: Why allur don't make a discord or something?
    December 03, 2018, 06:17:38 PM
  • Red Paradox: https://www.twitch.tv/flippay1985 everyday from 6:00pm
    May 29, 2018, 09:40:09 AM
  • Red Paradox: anyone play EA Sports UFC 3.. Looking for a challenge. PSN: Flippay1985 :)
    May 09, 2018, 11:00:52 PM
  • cold_187: @TriniXjin not really, I may have something they need (ssd/ram/mb etc.), hence why I also said "trade" ;)
    February 05, 2018, 10:22:14 AM

SimplePortal 2.3.3 © 2008-2010, SimplePortal