overview - temple universitycis-linux2.temple.edu/.../challenge_ms_dotnet/dotnet_d…  · web...

15
Creating a Simple Microsoft Visual Studio C# Web Form (with MySql Database Access) Table of Contents 1. Overview................................................................... 2 2. Using Visual Studio, Create New Web Application............................3 3. Reference MySql Database Driver............................................ 4 4. Quick Tour of the Visual Studio Interactive Development Environment........5 5. Add a Web Form to your Web Application.....................................6 6. Run Your Web Form.......................................................... 7 7. Create Clear Button Click Event (and Run the Web Form).....................8 8. Import SQL Classes into Your Web Form......................................9 9. Add Code Under the Show Data Button.......................................10 10..Net "View State"......................................................... 11 Note: some of the Visual Studio screen captures may not match your Visual Studio user interface exactly, but it should be close. Sally Kyvernitis, Temple University 1

Upload: hoangthuan

Post on 05-Feb-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

Creating a Simple Microsoft Visual Studio C# Web Form(with MySql Database Access)

Table of Contents

1. Overview....................................................................................................................................................................2

2. Using Visual Studio, Create New Web Application.....................................................................................................3

3. Reference MySql Database Driver.............................................................................................................................4

4. Quick Tour of the Visual Studio Interactive Development Environment....................................................................5

5. Add a Web Form to your Web Application................................................................................................................6

6. Run Your Web Form...................................................................................................................................................7

7. Create Clear Button Click Event (and Run the Web Form).........................................................................................8

8. Import SQL Classes into Your Web Form...................................................................................................................9

9. Add Code Under the Show Data Button...................................................................................................................10

10. .Net "View State".....................................................................................................................................................11

Note: some of the Visual Studio screen captures may not match your Visual Studio user interface exactly, but it should be close.

Sally Kyvernitis, Temple University 1

Page 2: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

1. Overview

In this tutorial, you will use Microsoft Visual Studio to create a simple C# web application (mostly copy/pasting code) to demonstrate how a .Net web app can read data from a MySql database. Your “web form” (Microsoft term for web page) will look like this when you first run it (see below left). Once the user clicks the “Show” button, it should like as shown below right.

The language you will use is "C#", which is basically Microsoft's version of Java (but legally could not name "Java" because it is interoperable only with Microsoft languages, not other open source implementations of Java.

NOTE: The Visual Studio (C#) code in this assignment was tested and then inserted into this Word document, but MSWord may have embedded formatting characters into the code. You may have to copy/paste the code “THROUGH” Notepad in order to remove those formatting characters. (This means, copy the code, paste into notepad, then copy from notepad and then paste into Visual Studio.)

Sally Kyvernitis, Temple University 2

Page 3: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

2. Using Visual Studio, Create New Web Application

Get into Visual Studio 2010: Start – All Programs – Visual Studio 2010. Click on: File – New - Project and select Visual C# (on the left pane) ASP.NET Web Application (in the middle pane) Give your project a name - “MyWebApp” was used below. Whatever you call it will become a folder under My

documents\ Visual Studio 2010\Projects.

Then select “Empty” template from the list of template options.

Sally Kyvernitis, Temple University 3

Select your G drive if you want to be able to open this project from another CIS lab PC later.

Page 4: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

3. Reference MySql Database Driver

Detach MySqlData.dll, the MySql database driver (for .Net), from blackboard and save it into the bin folder of your newly created .Net project:

My docs\Visual Studio\Projects\ProjectName\bin

From Solution explorer, right click the project (which may be "inside of" a group of projects called a "solution"), then click “add - reference”.

Click on the “Browse” tab then the browse button and locate MySql.Data.dll which you should have just stored into the bin folder of your project.

Sally Kyvernitis, Temple University 4

Page 5: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

4. Quick Tour of the Visual Studio Interactive Development Environment

This is what you see after creating the new project. You are looking at the HTML source for a web page. The file name extension for ASP.NET web pages is “.ASPX”. (The file name extension for Java Server Pages is “.JSP”). Toggle between Design View (how it will render in the browser) and Source View (the HTML code).

Sally Kyvernitis, Temple University 5

1. You are in Source View (shows HTML/CSS)

2. Click on Design View to see WYSIWYG.

Page 6: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

Sally Kyvernitis, Temple University 6

This is the WYSIWYG design view.

Toolbox is still over here. These are HTML items you can drag/drop onto your form. (push pin makes it auto-hide or stay open).

Project files over here.

Properties pane shows properties of whatever object is selected. The identifier for an object is called “(id)”.

Page 7: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

5. Add a Web Form to your Web Application

Remember that this is what we are trying to design:

Add a web form (named index.aspx) to your web application as shown below.

To adjust the properties of a form component (button or label), SINGLE CLICK on the component, then modify the (ID) or text property from the Properties pane (lower right corner) as shown in the table below. "(ID)" is like a variable name (how we reference the component from code). "text" is the value displayed by the component when the page is run.

(ID) which is the component's name text (the value it shows when run)1st button btnShow Show2nd button btnClear Clear

1st label dbMsg No Message Yet

Sally Kyvernitis, Temple University 7

1. Right click on the project name (“MyWebApp” in this example), select Add – New Item – Web form. Name the new form “index.aspx”.

2. Drag/Drop two buttons (for "Show" and "Clear") then click into the design are (after the buttons) & press Enter. 3. Type "Db Message" and "Db Data" (form constants), then4. Drag/Drop two labels onto the form (one to hold a possible Db Error and one to hold the displayed data).

Page 8: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

2nd label dbData No Data Yet

If you happen to double click on any of the four components, you'll be creating code for a click event for the component (as it is named probably before you had a chance to rename it). So, try not to double click. If you do double click on any component, it is probably easiest to delete index.aspx and recreate it.

The only reason we rename the button is so that when we create a button click event for that button, the name of the button click event will be self documenting: the event method will be named btnClear_Click(), not Button1_Click().

The (ID)s of the labels are only important because the code that you will copy/paste in expects the components to have the names (provided above).

Microsoft uses what they call a “flow layout”, in which you can drag an drop elements rather like a word document – if you drop an element in front of another element, the elements readjust to make space. You can click on the design view and hit enter to advance to a new line (like ending a paragraph in MSWord).

You can always go to “Source View” and type in HTML directly (such as divs and other layout), but be sure to drag/drop items that you will referencing from your program because .NET needs to manage these items for you.

6. Run Your Web Form

To run your Web Page, either right click on the page (in Design View or Source View) and select "View in Browser" or "Browse With" OR (if those are not available in VS 2015), select "Debug – Start Debugging" from the VS menu.

Design View Running

Sally Kyvernitis, Temple University 8

Page 9: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

Sally Kyvernitis, Temple University 9

Page 10: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

7. Create Clear Button Click Event (and Run the Web Form)

The first time you double click on a button from design mode, you create an event method. Subsequent times that you click on a button (from design mode), view the code for that button click event.

Double click on the btnClear button and you will find yourself in the “code behind file” index.aspx.cs (as it's called in .NET), inside a newly created method called btnClear_Click.

Type the following code into the btnClear_Click event (method). You may recognize the keyword “this” from java (means the object you are in, so in this case, it is the webform). When you type “this” then period then pause (like Netbeans), you get a pick list of legal values. So, type “this.d” and select dbMsg from the pick list. After you see this.dbMsg, type another period and pause so that you can see all the legal properties. Pick “Text” from the list. Picking from this list prevents many typos, especially when you are new to .Net development.

// THIS IS THE CODE UNDER THE Clear BUTTTON this.dbMsg.Text = ""; this.dbData.Text = "";

Run the Web Form (VS Menu option: "Debug – Start Debugging"). Click the "Clear" button and check that the button click event changes the text properties of the two labels on

the form.

Sally Kyvernitis, Temple University 10

Type code into the btnClear_Click() event method.

Page 11: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

8. Import SQL Classes into Your Web Form

At the very top of the Form code, you’ll see some “using” statements (which play the same role as java “import” statements). The Web Form (as created by VS) has some using statements already, but since we want to access a database, we must import the code from the MySql.Data.dll that we referenced earlier. To do this, type in the using statement shown below. Capitalization matters, be be careful with that. Type slowly and pause at every period – to take advantage of Visual Studio’s “intellisense”, which allows you to select (correct) values from a list instead of possibly mistyping them.

Sally Kyvernitis, Temple University 11

“using” statements are like “import” statements in Java.

“namespace” is like a java package. If two classes have the same name, the namespace differentiates which one you want.

Type here:

using MySql.Data.MySqlClient;

Page 12: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

9. Add Code Under the Show Data Button

From the design pane, double click on the show button. As you recall, this should create a btnShow_Click() event method. Past the following code INSIDE this newly created button click event (that already has the header, and braces). (You may have to “paste through” notepad to remove any MS formatting characters.) Then text that your code worked (VS Menu: "Debug – Start Debugging").

// This code goes into the btnShow Click event methodthis.dbData.Text = ""; // Clear values on form, if there are any.this.dbMsg.Text = "";

// Use this connection string if you are home, tunnelled in.string connectionString = "Data Source=cis-linux2.temple.edu; Port=3306; Database=SP11_1052_sallyk; User ID=sallyk; Password=Vaca1415"; // all on one line…

// Use this connection string if you are using a CIS dept PC.//string connectionString = "Data Source=localhost; Port=3307; Database=SP11_1052_sallyk; User ID=sallyk; Password=Vaca1415";

MySql.Data.MySqlClient.MySqlConnection conn = new MySqlConnection(connectionString);

try{ conn.Open(); // open the database connection

// Put the SQL (that you want to run) into a string variable. string sql = "select last_name, first_name from customer order by last_name, first_name";

// create a SqlCommand object (providing a SQL statement & an open DB connection) MySqlCommand command = new MySqlCommand(sql, conn);

// execute the sql command which (since it is a select statement) returns a result set MySqlDataReader reader = command.ExecuteReader();

this.dbData.Text = "<br/>"; while (reader.Read()) // display the data, one row at a time. { this.dbData.Text += reader["last_name"].ToString() + " - "; this.dbData.Text += reader["first_name"].ToString() + "<br/>"; }

reader.Close(); // close the database connection conn.Close(); // close the database connection (more important)}

catch (Exception ex){ this.dbMsg.Text = ex.Message; conn.Close();}

// This is the last line you type in. After this, there should be three braces// (close the btnShow event method, close the class, close the namespace).

Sally Kyvernitis, Temple University 12

Page 13: Overview - Temple Universitycis-linux2.temple.edu/.../challenge_MS_DotNet/DotNet_D…  · Web viewSql. Database. Access) Table of Contents. 1.Overview2. 2.Using Visual Studio, Create

10. .Net "View State"

Right click, and select “view source” to see what you have created… Some things should look familiar and some things new. .NET has something called a “ViewState” (see red text below) which stores encrypted values of all the user inputs. As a programmer, you typically don’t care what the value is.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head></head><body> <form method="post" action="index.aspx" id="form1"><div class="aspNetHidden"><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE0NDAzNjU4NjFkZNUkuXbTXqH4NhxA1zYUJqic3VKK9Qv2eBErNAWB7TPD" /></div><div class="aspNetHidden">

<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLa8a78CAL7nPWPAwKtkuWiCvC5fd3tSDTQEi6HCeQbXRDS4drgHxJC8k0uDMuXXWCN" /></div> <div> <input type="submit" name="btnShow" value="Show" id="btnShow" /> &nbsp;&nbsp;&nbsp; <input type="submit" name="btnClear" value="Clear" id="btnClear" /> <br /> <br /> Database message (if any):&nbsp; <span id="dbMsg">no message yet</span> <br /> <br /> Data:&nbsp; <span id="dbData">no data yet</span> <br /> <br /> </div> </form></body></html>

Now (back in the browser), click on the Show button and check that the Web Form is properly shows the data.

Right Click and View Source again. You should see the updated values within the HTML element with id "dbData", but also a much larger/updated View State that holds all the data in the form.

<span id="dbData">Bond – James <br/> claus – Santa <br/> …

</span>

Sally Kyvernitis, Temple University 13